Merge branch 'dev' into syntax-highlighter-unified

This commit is contained in:
Kam committed 2026-02-18 22:41:27 -05:00
commit df6beb4f15
207 files changed
+10330 -2705

No files matched your search

@@ -22,14 +22,17 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
@@ -364,6 +367,7 @@ public class AnimationController implements IAnimationHandler {
/**
* Get a built-in animation by name.
*
* @param name The animation name (case-insensitive)
* @return The built-in animation, or null if not found
*/
@@ -395,6 +399,7 @@ public class AnimationController implements IAnimationHandler {
/**
* Check if an animation name is a built-in animation.
*
* @param name The animation name to check
* @return true if this is a built-in animation
*/
@@ -7,7 +7,7 @@ import noppes.npcs.config.ConfigMarket;
/**
* Server-side utility for syncing auction configuration to clients.
* Handles Vault integration for currency name resolution.
*
* <p>
* This class is SERVER-SIDE ONLY. Client reads via AuctionClientConfig.
*/
public class AuctionConfigSync {
@@ -15,7 +15,7 @@ public class AuctionConfigSync {
/**
* Write auction config to NBT for sending to client.
* Called on server side when building login packet.
*
* <p>
* Currency name is resolved from Vault if enabled and available,
* otherwise falls back to ConfigMarket.CurrencyName.
*/
@@ -40,7 +40,7 @@ public class AuctionConfigSync {
public static String getEffectiveCurrencyName() {
if (ConfigMarket.UseVault && VaultUtil.isEnabled()) {
String vaultName = VaultUtil.getCurrencyNamePlural();
if (vaultName != null && !vaultName.isEmpty() && !vaultName.equals("coins")) {
if (vaultName != null && !vaultName.isEmpty()) {
return vaultName;
}
}
@@ -6,17 +6,18 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import noppes.npcs.CustomNpcs;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.EventHooks;
import noppes.npcs.LogWriter;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.api.handler.IAuctionHandler;
import noppes.npcs.api.handler.data.IAuctionListing;
import noppes.npcs.api.item.IItemStack;
import noppes.npcs.config.ConfigMarket;
import noppes.npcs.constants.EnumAuctionLogAction;
import noppes.npcs.constants.EnumAuctionSort;
import noppes.npcs.constants.EnumAuctionStatus;
import noppes.npcs.constants.EnumClaimType;
@@ -26,24 +27,32 @@ import noppes.npcs.controllers.data.AuctionClaim;
import noppes.npcs.controllers.data.AuctionFilter;
import noppes.npcs.controllers.data.AuctionListing;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.PlayerDataScript;
import noppes.npcs.controllers.data.PlayerTradeData;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.player.AuctionEvent;
import noppes.npcs.util.CustomNPCsThreader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Main controller for the Auction system.
*
* <p>
* Thread Safety:
* - Uses ConcurrentHashMap for all data stores - no locking required
* - Claims are stored in PlayerData, not here - reduces contention
* - Saves are performed asynchronously on the CNPC+ thread
*
* <p>
* Performance:
* - Auction processing runs every 30 seconds (600 ticks)
* - Save interval is every 30 seconds (600 ticks)
@@ -60,29 +69,41 @@ public class AuctionController implements IAuctionHandler {
// Player Indices for O(1) Lookups
// =========================================
/** Listings by seller UUID - for quick "my listings" lookups */
/**
* Listings by seller UUID - for quick "my listings" lookups
*/
private final Map<UUID, Set<String>> playerListingIds = new ConcurrentHashMap<>();
/** Listings where player is current high bidder */
/**
* Listings where player is current high bidder
*/
private final Map<UUID, Set<String>> playerBidIds = new ConcurrentHashMap<>();
/** Cached max trade slots per player - computed on login, cleared on logout */
/**
* Cached max trade slots per player - computed on login, cleared on logout
*/
private final Map<UUID, Integer> playerMaxTradesCache = new ConcurrentHashMap<>();
// =========================================
// Threading & State
// =========================================
/** Flag indicating data needs to be saved */
/**
* Flag indicating data needs to be saved
*/
private final AtomicBoolean dirty = new AtomicBoolean(false);
/** Flag to prevent concurrent saves */
/**
* Flag to prevent concurrent saves
*/
private final AtomicBoolean saving = new AtomicBoolean(false);
private String filePath = "";
private int tickCounter = 0;
/** Process auctions and save every 30 seconds (600 ticks) */
/**
* Process auctions and save every 30 seconds (600 ticks)
*/
private static final int TICK_INTERVAL = 600;
public AuctionController() {
@@ -138,52 +159,56 @@ public class AuctionController implements IAuctionHandler {
}
private void endAuction(AuctionListing listing) {
listing.status = EnumAuctionStatus.ENDED;
synchronized (listing) {
if (listing.status != EnumAuctionStatus.ACTIVE) return;
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
listing.status = EnumAuctionStatus.ENDED;
// Remove from bidder's active bids if any
if (listing.highBidderUUID != null) {
removeFromPlayerBids(listing.highBidderUUID, listing.id);
}
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
// Get item display name safely
String itemDisplayName = listing.item != null ? listing.item.getDisplayName() : "Unknown Item";
// Remove from bidder's active bids if any
if (listing.highBidderUUID != null) {
removeFromPlayerBids(listing.highBidderUUID, listing.id);
}
if (listing.hasBids()) {
// Auction sold - create claims
AuctionClaim itemClaim = AuctionClaim.createItemWonClaim(
listing.highBidderUUID, listing.highBidderName, listing.id, listing.item);
addClaimToPlayer(listing.highBidderUUID, itemClaim);
// Get item display name safely
String itemDisplayName = listing.item != null ? listing.item.getDisplayName() : "Unknown Item";
long saleAmount = listing.currentBid;
long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent);
long sellerReceives = saleAmount - tax;
if (listing.hasBids()) {
// Auction sold - create claims
AuctionClaim itemClaim = AuctionClaim.createItemWonClaim(
listing.highBidderUUID, listing.highBidderName, listing.id, listing.item);
addClaimToPlayer(listing.highBidderUUID, itemClaim);
AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim(
listing.sellerUUID, listing.sellerName, listing.id, sellerReceives,
itemDisplayName, listing.highBidderName);
addClaimToPlayer(listing.sellerUUID, currencyClaim);
long saleAmount = listing.currentBid;
long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent);
long sellerReceives = saleAmount - tax;
// Notifications
sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_WON, listing.id,
"You won the auction for " + itemDisplayName + "!");
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + itemDisplayName + " sold for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim(
listing.sellerUUID, listing.sellerName, listing.id, sellerReceives,
itemDisplayName, listing.highBidderName);
addClaimToPlayer(listing.sellerUUID, currencyClaim);
logAuction("SOLD", listing.sellerName, itemDisplayName, saleAmount,
"Winner: " + listing.highBidderName + ", Tax: " + tax);
} else {
// No bids - return item to seller
AuctionClaim returnClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, returnClaim);
// Notifications
sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_WON, listing.id,
"You won the auction for " + itemDisplayName + "!");
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + itemDisplayName + " sold for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_EXPIRED, listing.id,
"Your auction for " + itemDisplayName + " expired with no bids.");
logAuction(EnumAuctionLogAction.SOLD, listing.sellerName, itemDisplayName, saleAmount,
"Winner: " + listing.highBidderName + ", Tax: " + tax);
} else {
// No bids - return item to seller
AuctionClaim returnClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, returnClaim);
logAuction("EXPIRED", listing.sellerName, itemDisplayName, listing.startingPrice, "No bids");
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_EXPIRED, listing.id,
"Your auction for " + itemDisplayName + " expired with no bids.");
logAuction(EnumAuctionLogAction.EXPIRED, listing.sellerName, itemDisplayName, listing.startingPrice, "No bids");
}
}
}
@@ -280,6 +305,15 @@ public class AuctionController implements IAuctionHandler {
return "You cannot afford the listing fee (" + fee + " " + ConfigMarket.CurrencyName + ").";
}
// Fire auction create event (cancelable)
PlayerDataScript createHandler = ScriptController.Instance.getPlayerScripts(player);
IPlayer iCreator = (IPlayer) NpcAPI.Instance().getIEntity(player);
AuctionEvent.CreateEvent createEvent = new AuctionEvent.CreateEvent(
iCreator, NpcAPI.Instance().getIItemStack(item), startingPrice, buyoutPrice);
if (EventHooks.onAuctionCreate(createHandler, createEvent)) {
return "Auction creation was cancelled.";
}
// Deduct fee
if (!currency.withdraw(fee)) {
return "Failed to deduct listing fee.";
@@ -295,7 +329,7 @@ public class AuctionController implements IAuctionHandler {
markDirty();
logAuction("CREATED", playerName, item.getDisplayName(), startingPrice,
logAuction(EnumAuctionLogAction.CREATED, playerName, item.getDisplayName(), startingPrice,
"Buyout: " + (buyoutPrice > 0 ? buyoutPrice : "None") + ", Fee: " + fee);
return null; // Success
@@ -307,55 +341,74 @@ public class AuctionController implements IAuctionHandler {
return "Listing not found.";
}
if (!listing.status.canCancel()) {
return "This auction cannot be cancelled.";
synchronized (listing) {
if (!listing.status.canCancel()) {
return "This auction cannot be cancelled.";
}
UUID playerUUID = player.getUniqueID();
if (!isAdmin && !listing.isSeller(playerUUID)) {
return "You can only cancel your own listings.";
}
// Fire auction cancel event (cancelable)
PlayerDataScript cancelHandler = ScriptController.Instance.getPlayerScripts(player);
IPlayer iCanceller = (IPlayer) NpcAPI.Instance().getIEntity(player);
AuctionEvent.CancelEvent cancelEvent = new AuctionEvent.CancelEvent(iCanceller, listing, isAdmin);
if (EventHooks.onAuctionCancel(cancelHandler, cancelEvent)) {
return "Auction cancellation was prevented.";
}
// Handle penalty if there are bids
if (listing.hasBids()) {
long penalty = (long) (listing.currentBid * ConfigMarket.CancellationPenaltyPercent);
// Refund bidder (no item - can't rebid on cancelled auction)
AuctionClaim refundClaim = AuctionClaim.createRefundClaim(
listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid,
listing.item.getDisplayName(), listing.sellerName, null);
addClaimToPlayer(listing.highBidderUUID, refundClaim);
// Remove from bidder's active bids
removeFromPlayerBids(listing.highBidderUUID, listing.id);
sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id,
"The auction for " + listing.item.getDisplayName() + " was cancelled. Your bid has been refunded.");
// Return item to seller
AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, itemClaim);
// Deduct cancellation penalty from seller
if (penalty > 0) {
PlayerData sellerData = PlayerDataController.Instance.getData(listing.sellerUUID);
if (sellerData != null) {
sellerData.tradeData.withdraw(penalty);
sellerData.save();
}
}
logAuction(EnumAuctionLogAction.CANCELLED, listing.sellerName, listing.item.getDisplayName(), listing.currentBid,
"Penalty: " + penalty + ", Bidder refunded: " + listing.highBidderName +
(isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : ""));
} else {
// No bids - just return item
AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, itemClaim);
logAuction(EnumAuctionLogAction.CANCELLED, listing.sellerName, listing.item.getDisplayName(), listing.startingPrice,
"No bids" + (isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : ""));
}
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
listing.status = EnumAuctionStatus.CANCELLED;
markDirty();
}
UUID playerUUID = player.getUniqueID();
if (!isAdmin && !listing.isSeller(playerUUID)) {
return "You can only cancel your own listings.";
}
// Handle penalty if there are bids
if (listing.hasBids()) {
long penalty = (long) (listing.currentBid * ConfigMarket.CancellationPenaltyPercent);
// Refund bidder (no item - can't rebid on cancelled auction)
AuctionClaim refundClaim = AuctionClaim.createRefundClaim(
listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid,
listing.item.getDisplayName(), listing.sellerName, null);
addClaimToPlayer(listing.highBidderUUID, refundClaim);
// Remove from bidder's active bids
removeFromPlayerBids(listing.highBidderUUID, listing.id);
sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id,
"The auction for " + listing.item.getDisplayName() + " was cancelled. Your bid has been refunded.");
// Return item to seller
AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, itemClaim);
logAuction("CANCELLED", listing.sellerName, listing.item.getDisplayName(), listing.currentBid,
"Penalty: " + penalty + ", Bidder refunded: " + listing.highBidderName +
(isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : ""));
} else {
// No bids - just return item
AuctionClaim itemClaim = AuctionClaim.createItemReturnedClaim(
listing.sellerUUID, listing.sellerName, listing.id, listing.item);
addClaimToPlayer(listing.sellerUUID, itemClaim);
logAuction("CANCELLED", listing.sellerName, listing.item.getDisplayName(), listing.startingPrice,
"No bids" + (isAdmin ? ", Cancelled by admin: " + player.getCommandSenderName() : ""));
}
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
listing.status = EnumAuctionStatus.CANCELLED;
markDirty();
return null; // Success
}
@@ -376,75 +429,85 @@ public class AuctionController implements IAuctionHandler {
return "Listing not found.";
}
// Check status and expiry
if (!listing.status.canBid()) {
return "This auction has ended.";
synchronized (listing) {
// Check status and expiry
if (!listing.status.canBid()) {
return "This auction has ended.";
}
if (listing.isExpired()) {
return "This auction has ended.";
}
// CRITICAL: Prevent bidding on own items
if (listing.isSeller(playerUUID)) {
return "You cannot bid on your own auction.";
}
// Prevent rebidding if already highest bidder
if (listing.isHighBidder(playerUUID)) {
return "You are already the highest bidder. Use buyout if you want to purchase immediately.";
}
// Check minimum bid
long minBid = listing.getMinimumBid(ConfigMarket.MinBidIncrementPercent);
if (bidAmount < minBid) {
return "Bid must be at least " + minBid + " " + ConfigMarket.CurrencyName + ".";
}
// Check currency
PlayerData playerData = PlayerData.get(player);
if (playerData == null) {
return "Could not access player data.";
}
PlayerTradeData currency = playerData.tradeData;
// Store previous bidder info
UUID previousBidder = listing.highBidderUUID;
long previousBid = listing.currentBid;
// Full bid amount charged since we don't allow rebidding
long amountToCharge = bidAmount;
if (!currency.canAfford(amountToCharge)) {
return "You cannot afford this bid.";
}
// Fire auction bid event (cancelable)
PlayerDataScript bidHandler = ScriptController.Instance.getPlayerScripts(player);
IPlayer iBidder = (IPlayer) NpcAPI.Instance().getIEntity(player);
AuctionEvent.BidEvent bidEvent = new AuctionEvent.BidEvent(iBidder, listing, bidAmount);
if (EventHooks.onAuctionBid(bidHandler, bidEvent)) {
return "Bid was cancelled.";
}
// Deduct bid from new bidder FIRST
if (!currency.withdraw(amountToCharge)) {
return "Failed to deduct bid amount.";
}
// Refund previous bidder (include item for rebid option)
if (listing.hasBids() && previousBidder != null) {
AuctionClaim refundClaim = AuctionClaim.createRefundClaim(
previousBidder, listing.highBidderName, listing.id, previousBid,
listing.item.getDisplayName(), playerName, listing.item);
addClaimToPlayer(previousBidder, refundClaim);
// Remove from previous bidder's active bids
removeFromPlayerBids(previousBidder, listing.id);
sendNotificationToPlayer(previousBidder, EnumNotificationType.AUCTION_OUTBID, listing.id,
"You were outbid on " + listing.item.getDisplayName() + "!");
}
// Update listing
listing.highBidderUUID = playerUUID;
listing.highBidderName = playerName;
listing.currentBid = bidAmount;
listing.bidCount++;
}
if (listing.isExpired()) {
return "This auction has ended.";
}
// CRITICAL: Prevent bidding on own items
if (listing.isSeller(playerUUID)) {
return "You cannot bid on your own auction.";
}
// Prevent rebidding if already highest bidder
if (listing.isHighBidder(playerUUID)) {
return "You are already the highest bidder. Use buyout if you want to purchase immediately.";
}
// Check minimum bid
long minBid = listing.getMinimumBid(ConfigMarket.MinBidIncrementPercent);
if (bidAmount < minBid) {
return "Bid must be at least " + minBid + " " + ConfigMarket.CurrencyName + ".";
}
// Check currency
PlayerData playerData = PlayerData.get(player);
if (playerData == null) {
return "Could not access player data.";
}
PlayerTradeData currency = playerData.tradeData;
// Store previous bidder info
UUID previousBidder = listing.highBidderUUID;
long previousBid = listing.currentBid;
// Full bid amount charged since we don't allow rebidding
long amountToCharge = bidAmount;
if (!currency.canAfford(amountToCharge)) {
return "You cannot afford this bid.";
}
// Deduct bid from new bidder FIRST
if (!currency.withdraw(amountToCharge)) {
return "Failed to deduct bid amount.";
}
// Refund previous bidder (include item for rebid option)
if (listing.hasBids() && previousBidder != null) {
AuctionClaim refundClaim = AuctionClaim.createRefundClaim(
previousBidder, listing.highBidderName, listing.id, previousBid,
listing.item.getDisplayName(), playerName, listing.item);
addClaimToPlayer(previousBidder, refundClaim);
// Remove from previous bidder's active bids
removeFromPlayerBids(previousBidder, listing.id);
sendNotificationToPlayer(previousBidder, EnumNotificationType.AUCTION_OUTBID, listing.id,
"You were outbid on " + listing.item.getDisplayName() + "!");
}
// Update listing
listing.highBidderUUID = playerUUID;
listing.highBidderName = playerName;
listing.currentBid = bidAmount;
listing.bidCount++;
// Add to new bidder's active bids
addToPlayerBids(playerUUID, listing.id);
@@ -453,7 +516,7 @@ public class AuctionController implements IAuctionHandler {
markDirty();
logAuction("BID", playerName, listing.item.getDisplayName(), bidAmount,
logAuction(EnumAuctionLogAction.BID, playerName, listing.item.getDisplayName(), bidAmount,
"Bids: " + listing.bidCount + ", Seller: " + listing.sellerName);
return null; // Success
@@ -472,97 +535,107 @@ public class AuctionController implements IAuctionHandler {
return "Listing not found.";
}
// Check status and expiry
if (!listing.status.canBid()) {
return "This auction has ended.";
}
if (listing.isExpired()) {
return "This auction has ended.";
}
if (!listing.hasBuyout()) {
return "This auction does not have a buyout price.";
}
// CRITICAL: Prevent buying own items
if (listing.isSeller(playerUUID)) {
return "You cannot buy your own auction.";
}
// Check currency
PlayerData playerData = PlayerData.get(player);
if (playerData == null) {
return "Could not access player data.";
}
PlayerTradeData currency = playerData.tradeData;
// If buyer is already the high bidder, only charge the difference
boolean isCurrentBidder = listing.isHighBidder(playerUUID);
long amountToCharge = isCurrentBidder
? (listing.buyoutPrice - listing.currentBid)
: listing.buyoutPrice;
if (!currency.canAfford(amountToCharge)) {
if (isCurrentBidder) {
return "You cannot afford the remaining " + amountToCharge + " " + ConfigMarket.CurrencyName + " for buyout.";
synchronized (listing) {
// Check status and expiry
if (!listing.status.canBid()) {
return "This auction has ended.";
}
return "You cannot afford the buyout price.";
if (listing.isExpired()) {
return "This auction has ended.";
}
if (!listing.hasBuyout()) {
return "This auction does not have a buyout price.";
}
// CRITICAL: Prevent buying own items
if (listing.isSeller(playerUUID)) {
return "You cannot buy your own auction.";
}
// Check currency
PlayerData playerData = PlayerData.get(player);
if (playerData == null) {
return "Could not access player data.";
}
PlayerTradeData currency = playerData.tradeData;
// If buyer is already the high bidder, only charge the difference
boolean isCurrentBidder = listing.isHighBidder(playerUUID);
long amountToCharge = isCurrentBidder
? (listing.buyoutPrice - listing.currentBid)
: listing.buyoutPrice;
if (!currency.canAfford(amountToCharge)) {
if (isCurrentBidder) {
return "You cannot afford the remaining " + amountToCharge + " " + ConfigMarket.CurrencyName + " for buyout.";
}
return "You cannot afford the buyout price.";
}
// Fire auction buyout event (cancelable)
PlayerDataScript buyoutHandler = ScriptController.Instance.getPlayerScripts(player);
IPlayer iBuyer = (IPlayer) NpcAPI.Instance().getIEntity(player);
AuctionEvent.BuyoutEvent buyoutEvent = new AuctionEvent.BuyoutEvent(iBuyer, listing);
if (EventHooks.onAuctionBuyout(buyoutHandler, buyoutEvent)) {
return "Buyout was cancelled.";
}
// Deduct buyout amount
if (!currency.withdraw(amountToCharge)) {
return "Failed to deduct buyout amount.";
}
// Refund previous bidder if any AND they're not the buyer (no item - auction ended via buyout)
if (listing.hasBids() && listing.highBidderUUID != null && !isCurrentBidder) {
AuctionClaim refundClaim = AuctionClaim.createRefundClaim(
listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid,
listing.item.getDisplayName(), playerName, null);
addClaimToPlayer(listing.highBidderUUID, refundClaim);
// Remove from previous bidder's active bids
removeFromPlayerBids(listing.highBidderUUID, listing.id);
sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id,
"The auction for " + listing.item.getDisplayName() + " was bought out. Your bid has been refunded.");
} else if (isCurrentBidder) {
// Current bidder is buying out - just remove from their active bids
removeFromPlayerBids(playerUUID, listing.id);
}
// Create claims
AuctionClaim itemClaim = AuctionClaim.createItemWonClaim(playerUUID, playerName, listing.id, listing.item);
addClaimToPlayer(playerUUID, itemClaim);
long saleAmount = listing.buyoutPrice;
long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent);
long sellerReceives = saleAmount - tax;
AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim(
listing.sellerUUID, listing.sellerName, listing.id, sellerReceives,
listing.item.getDisplayName(), playerName);
addClaimToPlayer(listing.sellerUUID, currencyClaim);
// Notifications
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + listing.item.getDisplayName() + " was bought out for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
listing.status = EnumAuctionStatus.ENDED;
listing.highBidderUUID = playerUUID;
listing.highBidderName = playerName;
listing.currentBid = listing.buyoutPrice;
markDirty();
logAuction(EnumAuctionLogAction.BUYOUT, playerName, listing.item.getDisplayName(), listing.buyoutPrice,
"Seller: " + listing.sellerName + ", Tax: " + tax);
}
// Deduct buyout amount
if (!currency.withdraw(amountToCharge)) {
return "Failed to deduct buyout amount.";
}
// Refund previous bidder if any AND they're not the buyer (no item - auction ended via buyout)
if (listing.hasBids() && listing.highBidderUUID != null && !isCurrentBidder) {
AuctionClaim refundClaim = AuctionClaim.createRefundClaim(
listing.highBidderUUID, listing.highBidderName, listing.id, listing.currentBid,
listing.item.getDisplayName(), playerName, null);
addClaimToPlayer(listing.highBidderUUID, refundClaim);
// Remove from previous bidder's active bids
removeFromPlayerBids(listing.highBidderUUID, listing.id);
sendNotificationToPlayer(listing.highBidderUUID, EnumNotificationType.AUCTION_OUTBID, listing.id,
"The auction for " + listing.item.getDisplayName() + " was bought out. Your bid has been refunded.");
} else if (isCurrentBidder) {
// Current bidder is buying out - just remove from their active bids
removeFromPlayerBids(playerUUID, listing.id);
}
// Create claims
AuctionClaim itemClaim = AuctionClaim.createItemWonClaim(playerUUID, playerName, listing.id, listing.item);
addClaimToPlayer(playerUUID, itemClaim);
long saleAmount = listing.buyoutPrice;
long tax = (long) (saleAmount * ConfigMarket.SalesTaxPercent);
long sellerReceives = saleAmount - tax;
AuctionClaim currencyClaim = AuctionClaim.createCurrencyClaim(
listing.sellerUUID, listing.sellerName, listing.id, sellerReceives,
listing.item.getDisplayName(), playerName);
addClaimToPlayer(listing.sellerUUID, currencyClaim);
// Notifications
sendNotificationToPlayer(listing.sellerUUID, EnumNotificationType.AUCTION_SOLD, listing.id,
"Your " + listing.item.getDisplayName() + " was bought out for " + saleAmount + " " + ConfigMarket.CurrencyName + "!");
// Remove from seller's active listings
removeFromPlayerListings(listing.sellerUUID, listing.id);
listing.status = EnumAuctionStatus.ENDED;
listing.highBidderUUID = playerUUID;
listing.highBidderName = playerName;
listing.currentBid = listing.buyoutPrice;
markDirty();
logAuction("BUYOUT", playerName, listing.item.getDisplayName(), listing.buyoutPrice,
"Seller: " + listing.sellerName + ", Tax: " + tax);
return null; // Success
}
@@ -615,6 +688,14 @@ public class AuctionController implements IAuctionHandler {
return "Item data is missing.";
}
// Fire auction claim event (cancelable)
PlayerDataScript itemClaimHandler = ScriptController.Instance.getPlayerScripts(player);
IPlayer iItemClaimer = (IPlayer) NpcAPI.Instance().getIEntity(player);
AuctionEvent.ClaimEvent itemClaimEvent = new AuctionEvent.ClaimEvent(iItemClaimer, claim);
if (EventHooks.onAuctionClaim(itemClaimHandler, itemClaimEvent)) {
return "Claim was prevented.";
}
// Check inventory space
if (!player.inventory.addItemStackToInventory(claim.item.copy())) {
return "Your inventory is full.";
@@ -628,7 +709,7 @@ public class AuctionController implements IAuctionHandler {
// Cleanup listing if no more claims
cleanupListingIfComplete(claim.listingId);
logAuction("CLAIMED", player.getCommandSenderName(), claim.item.getDisplayName(), 0, "Item claimed");
logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), claim.item.getDisplayName(), 0, "Item claimed");
return null; // Success
}
@@ -652,6 +733,14 @@ public class AuctionController implements IAuctionHandler {
return "This is not a currency claim.";
}
// Fire auction claim event (cancelable)
PlayerDataScript currencyClaimHandler = ScriptController.Instance.getPlayerScripts(player);
IPlayer iCurrencyClaimer = (IPlayer) NpcAPI.Instance().getIEntity(player);
AuctionEvent.ClaimEvent currencyClaimEvent = new AuctionEvent.ClaimEvent(iCurrencyClaimer, claim);
if (EventHooks.onAuctionClaim(currencyClaimHandler, currencyClaimEvent)) {
return "Claim was prevented.";
}
if (!playerData.tradeData.deposit(claim.currency)) {
return "Failed to deposit currency.";
}
@@ -664,7 +753,7 @@ public class AuctionController implements IAuctionHandler {
// Cleanup listing if no more claims
cleanupListingIfComplete(claim.listingId);
logAuction("CLAIMED", player.getCommandSenderName(), ConfigMarket.CurrencyName, claim.currency,
logAuction(EnumAuctionLogAction.CLAIMED, player.getCommandSenderName(), ConfigMarket.CurrencyName, claim.currency,
claim.type == EnumClaimType.REFUND ? "Refund claimed" : "Sale proceeds claimed");
return null; // Success
@@ -993,7 +1082,7 @@ public class AuctionController implements IAuctionHandler {
if (expired > 0) {
playerData.updateClient = true;
playerData.save();
logAuction("CLAIM_EXPIRED", player.getCommandSenderName(), "Multiple", expired,
logAuction(EnumAuctionLogAction.CLAIM_EXPIRED, player.getCommandSenderName(), "Multiple", expired,
expired + " claims expired on login");
}
}
@@ -1041,52 +1130,28 @@ public class AuctionController implements IAuctionHandler {
// Logging
// =========================================
private void logAuction(String action, String playerName, String itemName, long amount, String details) {
if (!ConfigMarket.AuctionLoggingEnabled) return;
private void logAuction(EnumAuctionLogAction action, String playerName, String itemName, long amount, String details) {
if (!action.shouldLog()) return;
boolean shouldLog = false;
switch (action) {
case "CREATED":
shouldLog = ConfigMarket.LogAuctionCreated;
break;
case "BID":
shouldLog = ConfigMarket.LogAuctionBid;
break;
case "BUYOUT":
shouldLog = ConfigMarket.LogAuctionBuyout;
break;
case "SOLD":
shouldLog = ConfigMarket.LogAuctionSold;
break;
case "EXPIRED":
shouldLog = ConfigMarket.LogAuctionExpired;
break;
case "CANCELLED":
shouldLog = ConfigMarket.LogAuctionCancelled;
break;
case "CLAIMED":
case "CLAIM_EXPIRED":
shouldLog = ConfigMarket.LogAuctionClaimed;
break;
}
if (shouldLog) {
String logMessage = String.format("[AUCTION:%s] Player: %s, Item: %s, Amount: %d, Details: %s",
action, playerName, itemName, amount, details);
LogWriter.info(logMessage);
}
String logMessage = String.format("[AUCTION:%s] Player: %s, Item: %s, Amount: %d, Details: %s",
action.name(), playerName, itemName, amount, details);
LogWriter.info(logMessage);
}
// =========================================
// Save / Load - Async on CNPC+ Thread
// =========================================
/** Mark data as dirty - will be saved on next save cycle */
/**
* Mark data as dirty - will be saved on next save cycle
*/
private void markDirty() {
dirty.set(true);
}
/** Save synchronously - used for server shutdown */
/**
* Save synchronously - used for server shutdown
*/
public void save() {
if (!dirty.compareAndSet(true, false)) {
return; // Nothing to save
@@ -1094,7 +1159,9 @@ public class AuctionController implements IAuctionHandler {
saveInternal();
}
/** Save asynchronously on CNPC+ thread */
/**
* Save asynchronously on CNPC+ thread
*/
public void saveAsync() {
if (!dirty.compareAndSet(true, false)) {
return; // Nothing to save
@@ -1122,7 +1189,9 @@ public class AuctionController implements IAuctionHandler {
});
}
/** Internal synchronous save */
/**
* Internal synchronous save
*/
private void saveInternal() {
try {
NBTTagCompound compound = writeToNBT(new NBTTagCompound());
@@ -1141,7 +1210,9 @@ public class AuctionController implements IAuctionHandler {
File fileOld = new File(saveDir, "auction.dat_old");
File fileCurrent = new File(saveDir, "auction.dat");
CompressedStreamTools.writeCompressed(compound, new FileOutputStream(fileNew));
try (FileOutputStream fos = new FileOutputStream(fileNew)) {
CompressedStreamTools.writeCompressed(compound, fos);
}
// Backup rotation
if (fileOld.exists()) fileOld.delete();
@@ -1189,7 +1260,9 @@ public class AuctionController implements IAuctionHandler {
}
}
/** Rebuild all indices from loaded data */
/**
* Rebuild all indices from loaded data
*/
private void rebuildIndices() {
playerListingIds.clear();
playerBidIds.clear();
@@ -1210,7 +1283,10 @@ public class AuctionController implements IAuctionHandler {
}
private void loadFromFile(File file) throws Exception {
NBTTagCompound compound = CompressedStreamTools.readCompressed(new FileInputStream(file));
NBTTagCompound compound;
try (FileInputStream fis = new FileInputStream(file)) {
compound = CompressedStreamTools.readCompressed(fis);
}
readFromNBT(compound);
}
@@ -1398,15 +1474,20 @@ public class AuctionController implements IAuctionHandler {
}
public void adminCancelListing(String listingId, EntityPlayer admin, String reason) {
AuctionListing listing = listings.get(listingId);
String itemName = listing != null && listing.item != null ? listing.item.getDisplayName() : "Unknown";
cancelListing(listingId, admin, true);
if (reason != null && !reason.isEmpty()) {
logAuction(EnumAuctionLogAction.CANCELLED, admin.getCommandSenderName(), itemName, 0, "Admin cancel - Reason: " + reason);
}
}
public void clearEndedListings() {
// Remove ended/cancelled listings (claims are in PlayerData now)
listings.entrySet().removeIf(entry ->
entry.getValue().status == EnumAuctionStatus.CLAIMED ||
entry.getValue().status == EnumAuctionStatus.ENDED ||
entry.getValue().status == EnumAuctionStatus.CANCELLED);
entry.getValue().status == EnumAuctionStatus.ENDED ||
entry.getValue().status == EnumAuctionStatus.CANCELLED);
// Rebuild indices
rebuildIndices();
@@ -5,7 +5,7 @@ import noppes.npcs.config.ConfigScript;
/**
* Server-side utility for syncing script configuration to clients.
*
* <p>
* This class is SERVER-SIDE ONLY. Client reads via ScriptClientConfig.
*/
public class ScriptConfigSync {
@@ -2,11 +2,12 @@ package noppes.npcs.controllers;
import noppes.npcs.api.event.IAbilityEvent;
import noppes.npcs.api.event.IAnimationEvent;
import noppes.npcs.api.event.IPlayerAbilityEvent;
import noppes.npcs.api.event.IAuctionEvent;
import noppes.npcs.api.event.IBlockEvent;
import noppes.npcs.api.event.ICustomGuiEvent;
import noppes.npcs.api.event.ICustomNPCsEvent;
import noppes.npcs.api.event.IDialogEvent;
import noppes.npcs.api.event.IEnergyBarrierEvent;
import noppes.npcs.api.event.IEnergyProjectileEvent;
import noppes.npcs.api.event.IFactionEvent;
import noppes.npcs.api.event.IForgeEvent;
@@ -14,6 +15,7 @@ import noppes.npcs.api.event.IItemEvent;
import noppes.npcs.api.event.ILinkedItemEvent;
import noppes.npcs.api.event.INpcEvent;
import noppes.npcs.api.event.IPartyEvent;
import noppes.npcs.api.event.IPlayerAbilityEvent;
import noppes.npcs.api.event.IPlayerEvent;
import noppes.npcs.api.event.IProjectileEvent;
import noppes.npcs.api.event.IQuestEvent;
@@ -123,6 +125,12 @@ public class ScriptHookController implements IScriptHookHandler {
hook(NPC, ABILITY_INTERRUPT, IAbilityEvent.InterruptEvent.class);
hook(NPC, ABILITY_COMPLETE, IAbilityEvent.CompleteEvent.class);
// Energy Barrier
hook(NPC, ENERGY_BARRIER_SPAWNED, IEnergyBarrierEvent.SpawnedEvent.class);
hook(NPC, ENERGY_BARRIER_TICK, IEnergyBarrierEvent.UpdateEvent.class);
hook(NPC, ENERGY_BARRIER_HIT, IEnergyBarrierEvent.HitEvent.class);
hook(NPC, ENERGY_BARRIER_DESTROYED, IEnergyBarrierEvent.DestroyedEvent.class);
// Animation
hook(NPC, ANIMATION_START, IAnimationEvent.Started.class);
hook(NPC, ANIMATION_END, IAnimationEvent.Ended.class);
@@ -230,6 +238,12 @@ public class ScriptHookController implements IScriptHookHandler {
hook(PLAYER, ENERGY_PROJECTILE_BLOCK_IMPACT, IEnergyProjectileEvent.BlockImpactEvent.class);
hook(PLAYER, ENERGY_PROJECTILE_EXPIRED, IEnergyProjectileEvent.ExpiredEvent.class);
// Energy Barrier
hook(PLAYER, ENERGY_BARRIER_SPAWNED, IEnergyBarrierEvent.SpawnedEvent.class);
hook(PLAYER, ENERGY_BARRIER_TICK, IEnergyBarrierEvent.UpdateEvent.class);
hook(PLAYER, ENERGY_BARRIER_HIT, IEnergyBarrierEvent.HitEvent.class);
hook(PLAYER, ENERGY_BARRIER_DESTROYED, IEnergyBarrierEvent.DestroyedEvent.class);
// Ability
hook(PLAYER, ABILITY_START, IPlayerAbilityEvent.StartEvent.class);
hook(PLAYER, ABILITY_EXECUTE, IPlayerAbilityEvent.ExecuteEvent.class);
@@ -238,6 +252,13 @@ public class ScriptHookController implements IScriptHookHandler {
hook(PLAYER, ABILITY_INTERRUPT, IPlayerAbilityEvent.InterruptEvent.class);
hook(PLAYER, ABILITY_COMPLETE, IPlayerAbilityEvent.CompleteEvent.class);
// Auction
hook(PLAYER, AUCTION_CREATE, IAuctionEvent.CreateEvent.class);
hook(PLAYER, AUCTION_BID, IAuctionEvent.BidEvent.class);
hook(PLAYER, AUCTION_BUYOUT, IAuctionEvent.BuyoutEvent.class);
hook(PLAYER, AUCTION_CANCEL, IAuctionEvent.CancelEvent.class);
hook(PLAYER, AUCTION_CLAIM, IAuctionEvent.ClaimEvent.class);
// Profile
hook(PLAYER, PROFILE_CHANGE, IPlayerEvent.ProfileEvent.Changed.class);
hook(PLAYER, PROFILE_REMOVE, IPlayerEvent.ProfileEvent.Removed.class);
@@ -10,15 +10,16 @@ import noppes.npcs.config.ConfigMarket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
public class AuctionBlacklist {
private static Set<String> blacklistedItems = new HashSet<>();
private static Set<Pattern> wildcardPatterns = new HashSet<>();
private static Set<String> blacklistedMods = new HashSet<>();
private static Set<String> blacklistedNBTTags = new HashSet<>();
private static volatile Set<String> blacklistedItems = new HashSet<>();
private static volatile Set<Pattern> wildcardPatterns = new HashSet<>();
private static volatile Set<String> blacklistedMods = new HashSet<>();
private static volatile Set<String> blacklistedNBTTags = new HashSet<>();
// Built-in bound item requirement keys (always blocked)
private static final String SOULBIND_KEY = "cnpc_soulbind";
@@ -28,10 +29,10 @@ public class AuctionBlacklist {
private static final String BYPASS_PERMISSION = "customnpcs.auction.blacklist.bypass";
public static void reload() {
blacklistedItems.clear();
wildcardPatterns.clear();
blacklistedMods.clear();
blacklistedNBTTags.clear();
Set<String> newItems = new HashSet<>();
Set<Pattern> newWildcards = new HashSet<>();
Set<String> newMods = new HashSet<>();
Set<String> newNBTTags = new HashSet<>();
// Load blacklisted items
for (String item : ConfigMarket.BlacklistedItems) {
@@ -40,23 +41,29 @@ public class AuctionBlacklist {
if (item.contains("*")) {
String regex = "^" + item.replace(".", "\\.").replace("*", ".*") + "$";
wildcardPatterns.add(Pattern.compile(regex));
newWildcards.add(Pattern.compile(regex));
} else {
blacklistedItems.add(item);
newItems.add(item);
}
}
// Load blacklisted mods
for (String mod : ConfigMarket.BlacklistedMods) {
if (mod == null || mod.isEmpty()) continue;
blacklistedMods.add(mod.toLowerCase().trim());
newMods.add(mod.toLowerCase().trim());
}
// Load blacklisted NBT tags
for (String tag : ConfigMarket.BlacklistedNBTTags) {
if (tag == null || tag.isEmpty()) continue;
blacklistedNBTTags.add(tag.trim());
newNBTTags.add(tag.trim());
}
// Atomic swap
blacklistedItems = newItems;
wildcardPatterns = newWildcards;
blacklistedMods = newMods;
blacklistedNBTTags = newNBTTags;
}
/**
@@ -78,7 +85,6 @@ public class AuctionBlacklist {
* Check if item is blacklisted (without bypass check)
*/
public static boolean isBlacklisted(ItemStack item) {
if (!ConfigMarket.BlacklistEnabled) return false;
if (item == null || item.getItem() == null) return true;
// Check bound items (always blocked, even if blacklist is "disabled")
@@ -86,6 +92,8 @@ public class AuctionBlacklist {
return true;
}
if (!ConfigMarket.BlacklistEnabled) return false;
// Get registry name
GameRegistry.UniqueIdentifier uid = GameRegistry.findUniqueIdentifierFor(item.getItem());
if (uid == null) return true;
@@ -172,9 +180,13 @@ public class AuctionBlacklist {
if (registryName.contains("*")) {
String regex = "^" + registryName.replace(".", "\\.").replace("*", ".*") + "$";
wildcardPatterns.add(Pattern.compile(regex));
Set<Pattern> newWildcards = new HashSet<>(wildcardPatterns);
newWildcards.add(Pattern.compile(regex));
wildcardPatterns = newWildcards;
} else {
blacklistedItems.add(registryName);
Set<String> newItems = new HashSet<>(blacklistedItems);
newItems.add(registryName);
blacklistedItems = newItems;
}
return true;
}
@@ -185,30 +197,55 @@ public class AuctionBlacklist {
if (registryName.contains("*")) {
String regex = "^" + registryName.replace(".", "\\.").replace("*", ".*") + "$";
return wildcardPatterns.removeIf(p -> p.pattern().equals(regex));
Set<Pattern> newWildcards = new HashSet<>(wildcardPatterns);
boolean removed = false;
Iterator<Pattern> it = newWildcards.iterator();
while (it.hasNext()) {
if (it.next().pattern().equals(regex)) {
it.remove();
removed = true;
}
}
wildcardPatterns = newWildcards;
return removed;
} else {
return blacklistedItems.remove(registryName);
Set<String> newItems = new HashSet<>(blacklistedItems);
boolean removed = newItems.remove(registryName);
blacklistedItems = newItems;
return removed;
}
}
public static boolean addMod(String modId) {
if (modId == null || modId.isEmpty()) return false;
return blacklistedMods.add(modId.toLowerCase().trim());
Set<String> newMods = new HashSet<>(blacklistedMods);
boolean added = newMods.add(modId.toLowerCase().trim());
blacklistedMods = newMods;
return added;
}
public static boolean removeMod(String modId) {
if (modId == null || modId.isEmpty()) return false;
return blacklistedMods.remove(modId.toLowerCase().trim());
Set<String> newMods = new HashSet<>(blacklistedMods);
boolean removed = newMods.remove(modId.toLowerCase().trim());
blacklistedMods = newMods;
return removed;
}
public static boolean addNBTTag(String tag) {
if (tag == null || tag.isEmpty()) return false;
return blacklistedNBTTags.add(tag.trim());
Set<String> newTags = new HashSet<>(blacklistedNBTTags);
boolean added = newTags.add(tag.trim());
blacklistedNBTTags = newTags;
return added;
}
public static boolean removeNBTTag(String tag) {
if (tag == null || tag.isEmpty()) return false;
return blacklistedNBTTags.remove(tag.trim());
Set<String> newTags = new HashSet<>(blacklistedNBTTags);
boolean removed = newTags.remove(tag.trim());
blacklistedNBTTags = newTags;
return removed;
}
// =========================================
@@ -33,7 +33,9 @@ public class AuctionClaim implements IAuctionClaim {
this.otherPlayerName = "";
}
/** Create claim for winning an item (buyer won auction or buyout) */
/**
* Create claim for winning an item (buyer won auction or buyout)
*/
public static AuctionClaim createItemWonClaim(UUID playerUUID, String playerName, String listingId, ItemStack item) {
AuctionClaim claim = new AuctionClaim();
claim.playerUUID = playerUUID;
@@ -46,7 +48,9 @@ public class AuctionClaim implements IAuctionClaim {
return claim;
}
/** Create claim for returned item (seller's expired/cancelled listing) */
/**
* Create claim for returned item (seller's expired/cancelled listing)
*/
public static AuctionClaim createItemReturnedClaim(UUID playerUUID, String playerName, String listingId, ItemStack item) {
AuctionClaim claim = new AuctionClaim();
claim.playerUUID = playerUUID;
@@ -59,7 +63,9 @@ public class AuctionClaim implements IAuctionClaim {
return claim;
}
/** Create claim for seller's proceeds (stores item name for tooltip, not full item) */
/**
* Create claim for seller's proceeds (stores item name for tooltip, not full item)
*/
public static AuctionClaim createCurrencyClaim(UUID playerUUID, String playerName, String listingId, long currency, String itemName, String buyerName) {
AuctionClaim claim = new AuctionClaim();
claim.playerUUID = playerUUID;
@@ -74,7 +80,9 @@ public class AuctionClaim implements IAuctionClaim {
return claim;
}
/** Create claim for outbid refund (stores item for display and rebid option) */
/**
* Create claim for outbid refund (stores item for display and rebid option)
*/
public static AuctionClaim createRefundClaim(UUID playerUUID, String playerName, String listingId, long currency, String itemName, String outbidderName, ItemStack item) {
AuctionClaim claim = new AuctionClaim();
claim.playerUUID = playerUUID;
@@ -140,7 +148,7 @@ public class AuctionClaim implements IAuctionClaim {
@Override
public boolean isCurrencyClaim() {
return type == EnumClaimType.CURRENCY;
return type.isCurrency();
}
@Override
@@ -4,16 +4,12 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import noppes.npcs.constants.EnumAuctionSort;
import java.util.regex.Pattern;
/**
* Filter for auction listings.
* Supports search by item name or seller name and sorting options.
*/
public class AuctionFilter {
private static final Pattern COLOR_CODE_PATTERN = Pattern.compile("§[0-9a-fk-or]", Pattern.CASE_INSENSITIVE);
public String searchText;
private String searchText;
public EnumAuctionSort sortBy;
// Cached normalized search for efficiency
@@ -29,15 +25,18 @@ public class AuctionFilter {
return searchText != null && !searchText.trim().isEmpty();
}
/** Normalize string for search (strip colors, lowercase, trim) */
/**
* Normalize string for search (strip colors, lowercase, trim)
*/
public static String normalizeForSearch(String input) {
if (input == null || input.isEmpty()) return "";
String stripped = COLOR_CODE_PATTERN.matcher(input).replaceAll("");
stripped = EnumChatFormatting.getTextWithoutFormattingCodes(stripped);
return stripped.toLowerCase().trim();
String stripped = EnumChatFormatting.getTextWithoutFormattingCodes(input);
return stripped != null ? stripped.toLowerCase().trim() : input.toLowerCase().trim();
}
/** Check if item name or seller name matches search text */
/**
* Check if item name or seller name matches search text
*/
public boolean matchesSearch(String itemName, String sellerName) {
if (!hasSearchText()) return true;
String normalizedItem = normalizeForSearch(itemName);
@@ -46,12 +45,16 @@ public class AuctionFilter {
return normalizedItem.contains(normalizedSearch) || normalizedSeller.contains(normalizedSearch);
}
/** Legacy method - only checks item name */
/**
* Legacy method - only checks item name
*/
public boolean matchesSearch(String itemName) {
return matchesSearch(itemName, "");
}
/** Advanced search - all words must be present in item name OR seller name */
/**
* Advanced search - all words must be present in item name OR seller name
*/
public boolean matchesSearchAdvanced(String itemName, String sellerName) {
if (!hasSearchText()) return true;
String normalizedItem = normalizeForSearch(itemName);
@@ -68,7 +71,9 @@ public class AuctionFilter {
return true;
}
/** Legacy method - only checks item name */
/**
* Legacy method - only checks item name
*/
public boolean matchesSearchAdvanced(String itemName) {
return matchesSearchAdvanced(itemName, "");
}
@@ -106,13 +111,20 @@ public class AuctionFilter {
}
// Getters and setters
public String getSearchText() { return searchText; }
public String getSearchText() {
return searchText;
}
public void setSearchText(String searchText) {
this.searchText = searchText;
this.normalizedSearch = normalizeForSearch(searchText);
}
public EnumAuctionSort getSortBy() { return sortBy; }
public void setSortBy(EnumAuctionSort sortBy) { this.sortBy = sortBy; }
public EnumAuctionSort getSortBy() {
return sortBy;
}
public void setSortBy(EnumAuctionSort sortBy) {
this.sortBy = sortBy;
}
}
@@ -1,64 +0,0 @@
package noppes.npcs.controllers.data;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.constants.EnumNotificationType;
import java.util.UUID;
public class AuctionNotification {
public String id;
public UUID playerUUID;
public EnumNotificationType type;
public String listingId;
public String message;
public long timestamp;
public boolean sent;
public AuctionNotification() {
this.id = UUID.randomUUID().toString();
this.timestamp = System.currentTimeMillis();
this.sent = false;
}
public AuctionNotification(UUID playerUUID, EnumNotificationType type, String listingId, String message) {
this();
this.playerUUID = playerUUID;
this.type = type;
this.listingId = listingId;
this.message = message;
}
public boolean isForPlayer(UUID uuid) {
return playerUUID != null && playerUUID.equals(uuid);
}
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
compound.setString("ID", id);
compound.setString("PlayerUUID", playerUUID != null ? playerUUID.toString() : "");
compound.setInteger("Type", type.ordinal());
compound.setString("ListingID", listingId != null ? listingId : "");
compound.setString("Message", message != null ? message : "");
compound.setLong("Timestamp", timestamp);
compound.setBoolean("Sent", sent);
return compound;
}
public void readFromNBT(NBTTagCompound compound) {
id = compound.getString("ID");
String playerUUIDStr = compound.getString("PlayerUUID");
playerUUID = playerUUIDStr.isEmpty() ? null : UUID.fromString(playerUUIDStr);
type = EnumNotificationType.fromOrdinal(compound.getInteger("Type"));
listingId = compound.getString("ListingID");
message = compound.getString("Message");
timestamp = compound.getLong("Timestamp");
sent = compound.getBoolean("Sent");
}
public static AuctionNotification fromNBT(NBTTagCompound compound) {
AuctionNotification notification = new AuctionNotification();
notification.readFromNBT(compound);
return notification;
}
}
@@ -23,6 +23,7 @@ public class BuiltInAnimation extends Animation {
/**
* Built-in animations cannot be saved.
*
* @return this animation unchanged
*/
@Override
@@ -33,6 +34,7 @@ public class BuiltInAnimation extends Animation {
/**
* Built-in animations have no valid ID.
*
* @return always -1
*/
@Override
@@ -50,6 +52,7 @@ public class BuiltInAnimation extends Animation {
/**
* Check if this is a built-in animation.
*
* @return always true for BuiltInAnimation
*/
public boolean isBuiltIn() {
@@ -1,10 +1,15 @@
package noppes.npcs.controllers.data;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.IAbilityAction;
import kamkeel.npcs.controllers.data.ability.ToggleEntry;
import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket;
import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket;
import net.minecraft.entity.EntityLivingBase;
@@ -15,22 +20,18 @@ import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.util.DamageSource;
import noppes.npcs.AbstractDataAbilities;
import noppes.npcs.LogWriter;
import noppes.npcs.EventHooks;
import noppes.npcs.LogWriter;
import noppes.npcs.api.ability.IPlayerAbilityData;
import noppes.npcs.api.entity.IPlayer;
import noppes.npcs.controllers.AnimationController;
import noppes.npcs.controllers.ScriptController;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.scripted.NpcAPI;
import noppes.npcs.scripted.event.player.PlayerAbilityEvent;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilityStatePacket;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Manages player ability data - unlocked abilities, selection, cooldowns, and execution.
@@ -152,7 +153,7 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
@Override
protected void fireInterruptEvent(Ability ability, EntityLivingBase target,
DamageSource source, float damage) {
DamageSource source, float damage) {
EntityPlayer player = playerData.player;
if (ScriptController.Instance == null || player == null) return;
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player);
@@ -229,6 +230,11 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
}
@Override
protected void rollChainCooldown(ChainedAbility chain) {
cooldownEndTime = getWorldTime() + chain.getCooldownTicks();
}
@Override
protected void onAbilityComplete() {
currentAbility = null;
@@ -263,7 +269,10 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
return;
}
if (currentAbility != null && currentAbility.isExecuting()) {
// Tick active toggles (independent of currentAbility)
tickActiveToggles();
if (chainDelayRemaining > 0 || (currentAbility != null && currentAbility.isExecuting())) {
tickCurrentAbility();
// Apply rotation and position locks after ability tick
@@ -303,10 +312,27 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
/**
* Activate a specific ability by key.
* Prefix used to identify chained ability keys in the unlocked list.
*/
public static final String CHAIN_PREFIX = "chain:";
/**
* Resolve an action key to an IAbilityAction.
* Handles "chain:" prefix for chained abilities, otherwise resolves from AbilityController.
*/
private IAbilityAction resolveActionKey(String key) {
if (key.startsWith(CHAIN_PREFIX)) {
return AbilityController.Instance.resolveChainedAbility(key.substring(CHAIN_PREFIX.length()));
}
return AbilityController.Instance.resolveAbility(key);
}
/**
* Activate a specific ability by key. Keys prefixed with "chain:" are
* treated as chained abilities and resolved from {@link AbilityController}.
*
* @param player The player
* @param key The ability key (built-in or preset name)
* @param key The ability key (built-in or preset name), or "chain:name" for chains
* @return true if the ability was started
*/
public boolean activateAbility(EntityPlayer player, String key) {
@@ -314,20 +340,32 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
// Can't activate if already executing
if (currentAbility != null && currentAbility.isExecuting()) return false;
if (isExecutingChain()) return false;
// Resolve ability from controller
if (AbilityController.Instance == null) return false;
Ability ability = AbilityController.Instance.resolveAbility(key);
if (ability == null) return false;
// Resolve via unified resolver
IAbilityAction action = resolveActionKey(key);
if (action == null) return false;
// Check user type allows player
if (!ability.getAllowedBy().allowsPlayer()) return false;
// Check universal cooldown
if (!ability.isIgnoreCooldown() && isOnCooldown()) return false;
if (!action.getAllowedBy().allowsPlayer()) return false;
// Check conditions (skip target-requiring ones)
if (!ability.checkConditionsForPlayer(player)) return false;
if (!action.checkConditionsForPlayer(player)) return false;
// Dispatch: chain vs ability
if (action.isChain()) {
if (isOnCooldown()) return false;
currentAbilityKey = key;
currentTarget = null;
return startChain((ChainedAbility) action, null);
}
// Regular ability activation
Ability ability = (Ability) action;
// Check universal cooldown (abilities can optionally ignore it)
if (!ability.isIgnoreCooldown() && isOnCooldown()) return false;
// Fire extender start hook (e.g., resource cost checks)
if (!AbilityController.Instance.fireOnAbilityStart(ability, player, null)) {
@@ -385,6 +423,34 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
}
}
@Override
protected void onToggleStateChanged(String key, boolean active, int state) {
syncToClient();
}
@Override
protected boolean fireToggleEvent(Ability ability, int oldState, int newState) {
EntityPlayer player = playerData.player;
if (ScriptController.Instance == null || player == null) return false;
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player);
if (handler == null) return false;
IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player);
PlayerAbilityEvent.ToggleEvent event = new PlayerAbilityEvent.ToggleEvent(iPlayer, ability, oldState, newState);
return EventHooks.onPlayerAbilityToggle(handler, event);
}
@Override
protected boolean fireToggleUpdateEvent(Ability ability, int tick, int state) {
EntityPlayer player = playerData.player;
if (ScriptController.Instance == null || player == null) return true;
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(player);
if (handler == null) return true;
IPlayer iPlayer = (IPlayer) NpcAPI.Instance().getIEntity(player);
PlayerAbilityEvent.ToggleUpdateEvent event = new PlayerAbilityEvent.ToggleUpdateEvent(iPlayer, ability, tick, state);
EventHooks.onPlayerAbilityToggleUpdate(handler, event);
return event.isEnabled();
}
// ═══════════════════════════════════════════════════════════════════
// SELECTION
// ═══════════════════════════════════════════════════════════════════
@@ -540,6 +606,51 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
interruptCurrentAbility(null, 0);
}
// ═══════════════════════════════════════════════════════════════════
// DIMENSION CHANGE RESET
// ═══════════════════════════════════════════════════════════════════
/**
* Fully reset ability state when changing dimensions.
* Unlike interruptCurrentAbility(), this does NOT roll any cooldowns
* and ensures the player can immediately use abilities in the new dimension.
* Also re-syncs to client since the entity may be re-created.
*/
public void resetOnDimensionChange() {
// Clean up any executing ability without rolling cooldowns
if (currentAbility != null && currentAbility.isExecuting()) {
removeTelegraph(currentAbility);
currentAbility.cleanup();
currentAbility.interrupt();
stopAbilityAnimation();
releaseRotationControl();
releaseLockedPosition();
}
// Clear chain state
currentChain = null;
chainEntryIndex = -1;
chainDelayRemaining = -1;
// Clear all transient state
currentAbility = null;
currentAbilityKey = null;
currentTarget = null;
// Reset cooldowns completely
cooldownEndTime = 0;
interruptCooldownRolled = false;
// Sync cleared state to client
EntityPlayer player = playerData.player;
if (player != null) {
syncAbilityStateClear(player);
}
// Re-sync ability data (unlocked list, selection) to client
syncToClient();
}
// ═══════════════════════════════════════════════════════════════════
// DAMAGE HANDLING
// ═══════════════════════════════════════════════════════════════════
@@ -750,6 +861,16 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
compound.setTag("PlayerAbilities", list);
compound.setInteger("PlayerAbilitySelected", selectedIndex);
compound.setBoolean("AbilityAnimating", playingAbilityAnimation);
// Active toggles (compound format with state)
NBTTagList toggleList = new NBTTagList();
for (Map.Entry<String, ToggleEntry> entry : activeToggles.entrySet()) {
NBTTagCompound toggleNbt = new NBTTagCompound();
toggleNbt.setString("Key", entry.getKey());
toggleNbt.setInteger("State", entry.getValue().getState());
toggleList.appendTag(toggleNbt);
}
compound.setTag("ActiveToggles", toggleList);
}
public void readFromNBT(NBTTagCompound compound) {
@@ -772,11 +893,24 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
selectedIndex = Math.max(0, unlockedAbilities.size() - 1);
}
playingAbilityAnimation = compound.getBoolean("AbilityAnimating");
// Active toggles - restore state directly (no onToggleOn callback during load)
activeToggles.clear();
if (compound.hasKey("ActiveToggles")) {
NBTTagList toggleNbt = compound.getTagList("ActiveToggles", 10); // 10 = TAG_COMPOUND
for (int i = 0; i < toggleNbt.tagCount(); i++) {
NBTTagCompound entry = toggleNbt.getCompoundTagAt(i);
String key = entry.getString("Key");
int state = entry.hasKey("State") ? entry.getInteger("State") : 1;
setToggleEntryDirect(key, state);
}
}
}
/**
* Remove any unlocked ability keys that can no longer be resolved.
* Called during load to clean up references to deleted abilities.
* Supports both regular ability keys and "chain:" prefixed chained ability keys.
*/
private void validateUnlockedAbilities() {
if (AbilityController.Instance == null) return;
@@ -784,7 +918,8 @@ public class PlayerAbilityData extends AbstractDataAbilities implements IPlayerA
Iterator<String> it = unlockedAbilities.iterator();
while (it.hasNext()) {
String key = it.next();
if (!AbilityController.Instance.canResolveAbility(key)) {
IAbilityAction resolved = resolveActionKey(key);
if (resolved == null) {
it.remove();
LogWriter.info("Removed invalid ability reference from player data: " + key);
}
@@ -18,13 +18,13 @@ import noppes.npcs.LogWriter;
import noppes.npcs.api.ability.IPlayerAbilityData;
import noppes.npcs.api.entity.ICustomNpc;
import noppes.npcs.api.handler.IPlayerBankData;
import noppes.npcs.api.handler.IPlayerTradeData;
import noppes.npcs.api.handler.IPlayerData;
import noppes.npcs.api.handler.IPlayerDialogData;
import noppes.npcs.api.handler.IPlayerFactionData;
import noppes.npcs.api.handler.IPlayerItemGiverData;
import noppes.npcs.api.handler.IPlayerMailData;
import noppes.npcs.api.handler.IPlayerQuestData;
import noppes.npcs.api.handler.IPlayerTradeData;
import noppes.npcs.api.handler.IPlayerTransportData;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.constants.EnumRoleType;
@@ -47,8 +47,6 @@ import java.io.FileOutputStream;
import java.util.HashSet;
import java.util.UUID;
import static noppes.npcs.util.CustomNPCsThreader.customNPCThread;
public class PlayerData implements IExtendedEntityProperties, IPlayerData {
public PlayerDialogData dialogData = new PlayerDialogData(this);
public PlayerBankData bankData = new PlayerBankData(this);
@@ -8,7 +8,6 @@ import noppes.npcs.api.handler.data.IAuctionClaim;
import noppes.npcs.config.ConfigMarket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
@@ -129,12 +128,13 @@ public class PlayerTradeData implements IPlayerTradeData {
// Built-in currency
long newBalance = this.balance + amount;
if (newBalance > ConfigMarket.MaxBalance) {
return false;
}
// Overflow protection
if (newBalance < this.balance) {
// Overflow protection
return false;
newBalance = ConfigMarket.MaxBalance;
}
// Cap at MaxBalance instead of rejecting
if (newBalance > ConfigMarket.MaxBalance) {
newBalance = ConfigMarket.MaxBalance;
}
this.balance = newBalance;
this.lifetimeEarned += amount;
@@ -341,18 +341,16 @@ public class PlayerTradeData implements IPlayerTradeData {
*/
public int processExpiredClaims() {
int expirationDays = ConfigMarket.ClaimExpirationDays;
int removed = 0;
Iterator<AuctionClaim> iterator = claims.iterator();
while (iterator.hasNext()) {
AuctionClaim claim = iterator.next();
List<AuctionClaim> expired = new ArrayList<>();
for (AuctionClaim claim : claims) {
if (!claim.claimed && claim.isExpired(expirationDays)) {
claims.remove(claim);
removed++;
expired.add(claim);
}
}
return removed;
if (!expired.isEmpty()) {
claims.removeAll(expired);
}
return expired.size();
}
// =========================================
@@ -345,10 +345,10 @@ public class Action implements IAction {
try {
onStart.accept(this);
} catch (Throwable t) {
String err = "IAction" + getName() + " onStart threw an exception:";
String err = "IAction" + getName() + " onStart threw an exception:";
if (reportTo != null)
reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t));
manager.LOGGER.error("onStart Task of " + this + " threw an exception:", t);
}
@@ -384,7 +384,7 @@ public class Action implements IAction {
try {
onDone.accept(this);
} catch (Throwable t) {
String err = "IAction" + getName() + " onDone threw an exception:";
String err = "IAction" + getName() + " onDone threw an exception:";
if (reportTo != null)
reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t));
@@ -134,7 +134,7 @@ public class ConditionalAction extends Action implements IConditionalAction {
String err = "IConditionalAction '" + getName() + "' threw an exception:";
if (reportTo != null)
reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t));
manager.LOGGER.error("Task of " + this + " threw an exception:", t);
markDone();
}
@@ -151,7 +151,7 @@ public class ConditionalAction extends Action implements IConditionalAction {
try {
onTermination.accept(this);
} catch (Throwable t) {
String err = "IConditionalAction" + getName() + " onTermination threw an exception:";
String err = "IConditionalAction" + getName() + " onTermination threw an exception:";
if (reportTo != null)
reportTo.appendConsole(err + "\n" + ExceptionUtils.getStackTrace(t));