diff --git a/1.11_Market_Update.md b/1.11_Market_Update.md deleted file mode 100644 index 4236e0e63..000000000 --- a/1.11_Market_Update.md +++ /dev/null @@ -1,729 +0,0 @@ -# CustomNPC+ 1.11 Market Update - Implementation Plan - -## Overview - -The 1.11 Market Update introduces a comprehensive economy system for CustomNPC+: - -1. **Currency System** - Built-in CNPC+ currency with optional Vault integration -2. **Trader Enhancements** - Stock system, currency-based trades, reset timers -3. **Auction House** - Global auction system with bidding, buyout, and claims - ---- - -## 1. Currency System - -### Status: COMPLETE ✅ - -The currency system provides a unified economy for CNPC+ features. - -### Features -- **Built-in CNPC+ Currency** - Stored in PlayerData, persists across profile slots -- **Vault Integration** - Optional, when enabled all operations use Vault instead -- **Scripting API** - Full access via `IPlayer` methods -- **Unified Usage** - Both Trader and Auction systems use `PlayerCurrencyData` which auto-delegates to Vault - -### Vault Integration Flow -``` -┌─────────────────────────────────────────────────────────────────┐ -│ PlayerCurrencyData │ -│ │ -│ shouldUseVault() = ConfigMarket.UseVault && VaultUtil.isEnabled()│ -│ │ -│ ┌─────────────────────────────────────────────────────────────┐ │ -│ │ All methods check shouldUseVault() first: │ │ -│ │ - getBalance() → VaultUtil.getBalance() or local balance │ │ -│ │ - withdraw() → VaultUtil.withdrawMoney() or local │ │ -│ │ - deposit() → VaultUtil.addMoney() or local │ │ -│ │ - canAfford() → VaultUtil.has() or local check │ │ -│ └─────────────────────────────────────────────────────────────┘ │ -│ │ -│ Used by: ContainerNPCTrader, AuctionController │ -└─────────────────────────────────────────────────────────────────┘ -``` - -### Key Files -| File | Purpose | -|------|---------| -| `PlayerTradeData.java` | Per-player trade data (currency + auction claims), Vault delegation | -| `IPlayerTradeData.java` | API interface for trade operations (currency + claims) | -| `ConfigMarket.java` | Currency configuration (UseVault, CurrencyName, StartingBalance, MaxBalance) | -| `VaultUtil.java` | Vault API integration via reflection | - -### Configuration (ConfigMarket.java) -``` -Market.Currency: - - Use Vault: false - - Currency Name: "Coins" - - Starting Balance: 0 - - Max Balance: 2147483647 -``` - -### Scripting API (IPlayer) -```javascript -player.getCurrencyBalance() // Get balance -player.setCurrencyBalance(amount) // Set balance -player.depositCurrency(amount) // Add currency (returns success) -player.withdrawCurrency(amount) // Remove currency (returns success) -player.canAffordCurrency(amount) // Check if can afford -player.isUsingVaultCurrency() // Check if Vault is active -player.getFormattedCurrencyBalance() // Get formatted string - -// Via IPlayerData -player.getData().getTradeData() // Get IPlayerTradeData interface -``` - ---- - -## 2. Trader Enhancements - -### Status: COMPLETE ✅ - ---- - -### 2.1 Stock System - COMPLETE ✅ - -Traders can have limited stock that resets on configurable schedules. - -#### Stock Modes -| Mode | Description | Status | -|------|-------------|--------| -| **Global** | All players share the same stock pool | ✅ Working | -| **Per-Player** | Each player has their own stock counts | ✅ Working | - -#### Stock Reset Types (EnumStockReset) -| Type | Description | Status | -|------|-------------|--------| -| `NONE` | Stock never resets | ✅ Working | -| `MCDAILY` | Resets every MC day (24000 ticks) | ✅ Working | -| `MCWEEKLY` | Resets every 7 MC days (168000 ticks) | ✅ Working | -| `MCCUSTOM` | Custom MC tick interval | ✅ Working | -| `RLDAILY` | Resets every 24 real-life hours | ✅ Working | -| `RLWEEKLY` | Resets every 7 real-life days | ✅ Working | -| `RLCUSTOM` | Custom real-time interval | ✅ Working | - -#### Stock UI Features - COMPLETE ✅ -| Feature | Status | Notes | -|---------|--------|-------| -| Stock count per item | ✅ | Shows to right of output slot | -| Out of stock indicator | ✅ | Dark overlay + red count | -| Reset timer countdown | ✅ | Real-time client-side countdown in top-right | -| "Reopen Trader" message | ✅ | Shows when countdown reaches 0 | -| Admin stock configuration | ✅ | SubGuiNpcTraderStock | -| Per-slot stock limits | ✅ | SubGuiNpcTraderStockSlots | -| Reset stock button | ✅ | With confirmation dialog | -| Reset cooldown button | ✅ | With confirmation dialog | - ---- - -### 2.2 Trader Currency Support - COMPLETE ✅ - -Trades can require BOTH items AND currency (additive costs). Uses `PlayerCurrencyData` which auto-delegates to Vault when enabled. - -#### Trade Entry Structure -Each trade slot can have: -- **Sold Item** - What the player receives ✅ -- **Currency 1** - First item cost (existing) ✅ -- **Currency 2** - Second item cost (existing) ✅ -- **Currency Cost** - CNPC+ Currency / Vault cost ✅ NEW - -#### Implementation Details -- Currency cost stored as `long[] currencyCost[18]` in RoleTrader -- Uses `data.tradeData.getBalance()` and `data.tradeData.withdraw()` -- Automatically uses Vault when `ConfigMarket.UseVault` is enabled -- NBT serialization for persistence ✅ - ---- - -### 2.3 Player Trader GUI - COMPLETE ✅ - -#### Display Features -| Element | Position | Status | -|---------|----------|--------| -| "Trader" label | Top-left | ✅ | -| Reset countdown | Top-right | ✅ Real-time ticking | -| Stock count | Right of each trade | ✅ Green/Red | -| Player balance | Bottom-right | ✅ | -| Status message | Bottom-left | ✅ On hover | - ---- - -### 2.4 Multi-Player Sync - COMPLETE ✅ - -MarketRegistry provides linked market synchronization across all NPCs sharing the same market. - ---- - -### 2.5 Scripting API - COMPLETE ✅ - -Full API available via `IRoleTrader` interface. - ---- - -## 3. Auction House System - -### Status: COMPLETE ✅ - -### 3.1 Architecture Overview - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ AuctionController │ -│ - Manages auction listings with player indices │ -│ - Handles listing/bidding/buyout logic │ -│ - Uses ConcurrentHashMap for thread-safety (no locks) │ -│ - Async saves on CNPC+ thread every 30 seconds │ -│ - 30-second update cycle for processing ended auctions │ -└─────────────────────────────────────────────────────────────────┘ - │ - Uses PlayerCurrencyData (Vault-aware) - │ -┌─────────────────────────────────────────────────────────────────┐ -│ PlayerTradeData │ -│ - Combined currency + auction claims (shared across profiles) │ -│ - Currency: Vault integration with local fallback │ -│ - Claims: Thread-safe CopyOnWriteArrayList for async additions │ -│ - Expired claims processed on login │ -│ - Notifications sent immediately to online players │ -└─────────────────────────────────────────────────────────────────┘ -``` - -### 3.2 Vault Integration - -The Auction system uses `PlayerCurrencyData` for all currency operations: -- `AuctionController.createListing()` → `currencyData.withdraw(fee)` -- `AuctionController.placeBid()` → `currencyData.withdraw(bidAmount)` -- `AuctionController.buyout()` → `currencyData.withdraw(buyoutPrice)` -- `AuctionController.claimCurrency()` → `currencyData.deposit(amount)` - -**When Vault is enabled** (`ConfigMarket.UseVault = true`): -- All operations automatically use Vault economy -- No code changes required - `PlayerCurrencyData` handles delegation - -### 3.3 GUI Structure - -``` -GuiAuctionInterface (Base GUI - opened via Auctioneer NPC) - │ - ├── GuiAuctionListing (Browse auctions - PAGE_LISTINGS) - │ - 9x5 grid of auction items - │ - Filter button with tooltip showing current settings - │ - Click item → Opens GuiAuctionBidding - │ - Pagination with up/down arrows - │ - ├── GuiAuctionSell (Create new listing - PAGE_SELL) - │ - Sell slot for item to auction (cloned from inventory) - │ - Click inventory: left=add stack, right=add 1 - │ - Click sell slot: left=clear, right=remove 1 - │ - Starting price + buyout price text fields - │ - Allow Buyout toggle button - │ - Listing fee display - │ - Confirm button with coin icon - │ - ├── GuiAuctionTrades (My Trades - PAGE_CLAIMS) - │ - 9x5 grid showing: active listings, active bids, claims - │ - Blue tint: active listings/bids - │ - Green tint: claimable items - │ - Red tint: refunds - │ - Confirmation system for cancel/claim operations - │ - ├── GuiAuctionBidding (View listing details) - │ - Item display slot - │ - Auction info (seller, price, time, bids) - │ - Bid button → SubGuiAuctionBid - │ - Buy Now button → SubGuiAuctionBuyNow - │ - Own listings: buttons hidden, view-only - │ - ├── SubGuiAuctionBid (Bid confirmation popup) - │ - Shows minimum bid, player balance - │ - Bid amount input field - │ - Place Bid / Cancel buttons - │ - ├── SubGuiAuctionBuyNow (Buyout confirmation popup) - │ - Shows buyout price, player balance - │ - Yes / Cancel buttons - │ - └── SubGuiAuctionSearch (Filter popup) - - Search text input - - Apply/Cancel buttons -``` - -### 3.4 Client Config Sync - -The client uses `AuctionClientConfig` to cache server settings: -- Synced via `LoginPacket` on player join -- Client never uses `ConfigMarket` directly for display -- Ensures server authority over fees, currency name, etc. - -```java -// Server sends config in LoginPacket -AuctionClientConfig.writeToNBT(compound); // Server side - -// Client receives and caches -AuctionClientConfig.readFromNBT(compound); // Client side - -// Client GUI uses cached values -AuctionClientConfig.getListingFee(); -AuctionClientConfig.getCurrencyName(); -AuctionClientConfig.getMinBidIncrement(); -``` - -### 3.5 Data Structures - -#### AuctionListing -```java -public class AuctionListing { - String id; // Unique listing ID (UUID-based) - UUID sellerUUID; // Seller's UUID - String sellerName; // Seller's display name - ItemStack item; // Item being sold - long startingPrice; // Minimum starting bid - long buyoutPrice; // Instant buy price (0 = no buyout) - long currentBid; // Current highest bid - UUID highBidderUUID; // Current high bidder (null if no bids) - String highBidderName; // High bidder display name - int bidCount; // Number of bids placed - long createdTime; // When listing was created - long endTime; // When auction ends - EnumAuctionStatus status; // ACTIVE, ENDED, CANCELLED, CLAIMED -} -``` - -#### AuctionClaim -```java -public class AuctionClaim { - String id; // Unique claim ID - UUID playerUUID; // Player who can claim - String listingId; // Related auction listing - EnumClaimType type; // ITEM, CURRENCY, REFUND - ItemStack item; // Item to claim (if type = ITEM) - long currency; // Currency to claim (if type = CURRENCY/REFUND) - long createdTime; // When claim was created - boolean claimed; // Whether claimed -} -``` - -### 3.6 Security Features - -All actions are validated server-side: - -| Check | Location | Description | -|-------|----------|-------------| -| Own item bid prevention | `placeBid()` | `listing.isSeller(playerUUID)` check | -| Own item buyout prevention | `buyout()` | `listing.isSeller(playerUUID)` check | -| Auction expiry check | `placeBid()/buyout()` | Double-check inside write lock | -| Currency validation | All actions | Verify balance before operations | -| Claim ownership | `claimItem()/claimCurrency()` | `claim.isForPlayer(playerUUID)` check | -| Blacklist check | `createListing()` | `AuctionBlacklist.isBlacklistedForPlayer()` check | -| Bound item check | `createListing()` | Auto-blocks Soulbound/Profile-Slotbound items | - -### 3.7 Snipe Protection - -When a bid is placed with less than `SnipeProtectionMinutes` remaining: -- Extend the auction end time TO `SnipeProtectionMinutes` from now -- Never extend beyond `SnipeProtectionMinutes` -- Default: 2 minutes - -Example: Auction ends in 30 seconds, someone bids → Timer resets to 2:00 - ---- - -### 3.8 Item Blacklist System - -Prevents specific items from being listed on the auction house. - -#### Blacklist Types - -| Type | Description | Example | -|------|-------------|---------| -| **Items** | Block specific items by registry name | `minecraft:diamond_sword` | -| **Wildcards** | Block items matching pattern | `minecraft:diamond*` | -| **Mods** | Block all items from a mod | `customnpcs` | -| **NBT Tags** | Block items with specific NBT | `ench` (enchanted items) | - -#### Auto-Blocked Items (Always Blocked) - -These items are **always** blocked regardless of blacklist settings: -- **Soulbound Items** - Items with `cnpc_soulbind` requirement -- **Profile-Slotbound Items** - Items with `cnpc_profile_slot` requirement - -The system checks for these under `RPGCore/Requirements` in the item's NBT. - -#### Bypass Permission - -Players with OP status or the `customnpcs.auction.blacklist.bypass` permission can list blacklisted items. - -#### Configuration - -``` -Market.Auction.Blacklist: - Enabled: true - BlacklistedItems: ["minecraft:barrier", "minecraft:command_block*"] - BlacklistedMods: [] - BlacklistedNBTTags: [] -``` - -#### Commands - -| Command | Description | -|---------|-------------| -| `/cnpc auction blacklist add ` | Add to blacklist (runtime only) | -| `/cnpc auction blacklist remove ` | Remove from blacklist (runtime only) | -| `/cnpc auction blacklist list [item\|mod\|nbt]` | List blacklisted entries | -| `/cnpc auction blacklist reload` | Reload blacklist from config | -| `/cnpc auction blacklist check` | Check if held item is blacklisted | - ---- - -## 4. AuctionController Performance & Thread Safety - -### 4.1 Threading Model - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ AuctionController │ -│ │ -│ ┌─────────────────────┐ ┌─────────────────┐ ┌───────────────┐ │ -│ │ ConcurrentHashMap │ │ AtomicBoolean │ │ CNPC+ Thread │ │ -│ │ (listings, indices) │ │ dirty, saving │ │ (async saves) │ │ -│ └─────────────────────┘ └─────────────────┘ └───────────────┘ │ -│ │ -│ All operations use ConcurrentHashMap - no explicit locking │ -│ Minecraft is single-threaded for gameplay - inherent safety │ -│ Async saves snapshot data before writing to disk │ -└─────────────────────────────────────────────────────────────────┘ - │ -┌─────────────────────────────────────────────────────────────────┐ -│ PlayerTradeData │ -│ │ -│ ┌─────────────────────────────────────────────────────────────┐ │ -│ │ Currency: long balance (or Vault delegation) │ │ -│ │ Claims: CopyOnWriteArrayList │ │ -│ │ - Thread-safe for concurrent read/write │ │ -│ │ - Claims can be added from CNPC+ thread for offline players │ │ -│ │ - Stored in PlayerData (persisted with player, not auctions) │ │ -│ └─────────────────────────────────────────────────────────────┘ │ -└─────────────────────────────────────────────────────────────────┘ -``` - -### 4.2 Player Indices for O(1) Lookups - -| Index | Type | Purpose | -|-------|------|---------| -| `playerListingIds` | `Map>` | Active listings by seller | -| `playerBidIds` | `Map>` | Listings where player has active bid | - -**Claims are now stored in PlayerData:** -- `PlayerTradeData.claims` - CopyOnWriteArrayList per player -- Accessed via `PlayerData.get(player).tradeData` -- Shared across all profile slots (combined with currency) - -**Performance Impact:** -- `getPlayerListingCount()`: O(n) → O(1) -- `getPlayerActiveListings()`: O(n) → O(k) where k = player's listings -- `getPlayerActiveBids()`: O(n) → O(k) -- `getPlayerClaims()`: Direct access to player's claims list - -### 4.3 Update Intervals - -| Operation | Interval | Rationale | -|-----------|----------|-----------| -| Process ended auctions | 30 seconds (600 ticks) | Reduces server load | -| Save auction data | 30 seconds (600 ticks) | Batches writes, reduces I/O | -| Process expired claims | On player login | Per-player, not global tick | - -### 4.4 Data Safety - -1. **Currency Deduction** - Withdraw before updating listing -2. **Previous Bidder Refund** - Store info before modification -3. **Concurrent Saves** - `AtomicBoolean` prevents duplicates -4. **Offline Player Claims** - Loaded async on CNPC+ thread, saved to PlayerData -5. **Claim Migration** - Old claims in auction.dat migrated to PlayerData on load - -### 4.5 Server Shutdown Handling - -On `FMLServerStoppedEvent`: -1. `AuctionController.save()` called synchronously -2. Uses CNPC+ thread (single-threaded executor) -3. All pending saves complete before shutdown - ---- - -## 5. File Structure - -### New Files Created - -``` -constants/ - EnumAuctionStatus.java ✅ - EnumAuctionSort.java ✅ - EnumClaimType.java ✅ - EnumNotificationType.java ✅ - -controllers/ - AuctionController.java ✅ (with threading, indices, Vault support) - AuctionConfigSync.java ✅ (server-side config sync utility) - -controllers/data/ - AuctionListing.java ✅ - AuctionClaim.java ✅ - AuctionFilter.java ✅ - AuctionBlacklist.java ✅ (item blacklist checking + bypass) - PlayerTradeData.java ✅ (currency + claims storage per player) - -roles/ - RoleAuctioneer.java ✅ - -containers/ - ContainerAuction.java ✅ - ContainerAuctionListing.java ✅ - ContainerAuctionBidding.java ✅ - ContainerAuctionTrades.java ✅ - ContainerAuctionSell.java ✅ - InventoryAuctionDisplay.java ✅ - SlotAuctionDisplay.java ✅ - -client/ - AuctionClientConfig.java ✅ (client-side config cache) - -client/gui/player/ - GuiAuctionInterface.java ✅ - GuiAuctionListing.java ✅ - GuiAuctionSell.java ✅ - GuiAuctionTrades.java ✅ - GuiAuctionBidding.java ✅ - SubGuiAuctionSearch.java ✅ - SubGuiAuctionBid.java ✅ - SubGuiAuctionBuyNow.java ✅ - AuctionTooltipHandler.java ✅ - -client/gui/util/ - GuiAuctionNavButton.java ✅ - -network/packets/player/ - AuctionActionPacket.java ✅ -``` - -### New Commands - -``` -command/ - AuctionCommand.java ✅ /cnpc auction with list, view, open, blacklist - command/auction/ - BlacklistSubCommand.java ✅ /cnpc auction blacklist subcommands -``` - -### Files Modified - -``` -CustomNpcs.java ✅ Initialize AuctionController, save on shutdown -EnumRoleType.java ✅ Added Auctioneer -EnumGuiType.java ✅ Added PlayerAuction, PlayerAuctionSell, PlayerAuctionTrades, PlayerAuctionBidding -EnumPlayerPacket.java ✅ Added AuctionData, AuctionAction -CommonProxy.java ✅ Handle auction container types -ClientProxy.java ✅ Handle auction GUI types -DataAdvanced.java ✅ Handle Auctioneer role -ConfigMarket.java ✅ Added Auction section -LoginPacket.java ✅ Sync auction config to client -PlayerData.java ✅ Added tradeData field (currency + claims, shared across profiles) -en_US.lang ✅ Added auction lang keys -``` - ---- - -## 6. Configuration - -### ConfigMarket.java Structure - -```java -// ========================================= -// Currency (Market.Currency) -// ========================================= -public static boolean UseVault = false; // Use Vault economy -public static String CurrencyName = "Coins"; // Display name -public static long StartingBalance = 0; // New player balance -public static long MaxBalance = Long.MAX_VALUE; // Balance cap - -// ========================================= -// Auction (Market.Auction) -// ========================================= -public static final int MAX_TRADE_SLOTS = 45; // 9x5 grid maximum -public static final int MIN_TRADE_SLOTS = 1; // Minimum allowed - -public static boolean AuctionEnabled = true; -public static int AuctionDurationHours = 24; // Auction length (hours) -public static long ListingFee = 10; // Fee to create listing -public static long MinimumListingPrice = 1; // Minimum starting price -public static double SalesTaxPercent = 0.05; // 5% tax on sales -public static int DefaultMaxTrades = 8; // Per player (listings + bids + claims) -public static int SnipeProtectionMinutes = 2; // Anti-snipe timer -public static int ClaimExpirationDays = 20; // Days before unclaimed deleted -public static double MinBidIncrementPercent = 0.05; // 5% minimum bid increase - -// ========================================= -// Auction Logging -// ========================================= -public static boolean AuctionLoggingEnabled = false; -public static boolean LogAuctionCreated = true; -public static boolean LogAuctionBid = true; -public static boolean LogAuctionBuyout = true; -public static boolean LogAuctionSold = true; -public static boolean LogAuctionExpired = true; -public static boolean LogAuctionCancelled = true; -public static boolean LogAuctionClaimed = true; - -// ========================================= -// Auction Blacklist (Market.Auction.Blacklist) -// ========================================= -public static boolean BlacklistEnabled = true; -public static String[] BlacklistedItems = {}; // Registry names (supports wildcards) -public static String[] BlacklistedMods = {}; // Mod IDs to block entirely -public static String[] BlacklistedNBTTags = {}; // NBT tag keys to block -``` - -### Auction Permissions - -| Permission | Description | -|------------|-------------| -| `customnpcs.auction.trades.*` | Unlimited trade slots (up to 45) | -| `customnpcs.auction.trades.X` | Exactly X trade slots (where X is 1-45) | -| `customnpcs.auction.blacklist.bypass` | Bypass item blacklist restrictions | - -**Trade Slot Permissions:** -- Default is 8 trade slots -- Permissions only **increase** the limit (permissions below 8 are ignored) -- Maximum is capped at 45 (9x5 grid) -- Trade slots = Active Listings + Active Bids + Pending Claims - -**Blacklist Bypass:** -- OP players or those with `customnpcs.auction.blacklist.bypass` can list blacklisted items -- Soulbound and Profile-Slotbound items are **always** blocked (no bypass) - ---- - -## 7. Commands - -### `/cnpc auction` Command - -Allows interaction with the Auction House without needing an Auctioneer NPC. - -| Subcommand | Usage | Permission | Description | -|------------|-------|------------|-------------| -| `list` | `/cnpc auction list [page]` | OP | View active auctions in chat | -| `view` | `/cnpc auction view ` | OP | View a player's auction activity | -| `open` | `/cnpc auction open` | Any | Opens the Auction House GUI | - -**Examples:** -``` -/cnpc auction list - Show first page of active auctions -/cnpc auction list 2 - Show page 2 of auctions -/cnpc auction view Steve - Show Steve's listings, bids, and claims -/cnpc auction open - Open the full Auction House GUI -``` - -### `/cnpc auction blacklist` Command - -Manage the auction item blacklist (runtime changes, not persisted to config). - -| Subcommand | Usage | Permission | Description | -|------------|-------|------------|-------------| -| `add` | `/cnpc auction blacklist add ` | OP | Add to blacklist | -| `remove` | `/cnpc auction blacklist remove ` | OP | Remove from blacklist | -| `list` | `/cnpc auction blacklist list [item\|mod\|nbt]` | OP | List blacklisted entries | -| `reload` | `/cnpc auction blacklist reload` | OP | Reload from config | -| `check` | `/cnpc auction blacklist check` | Any | Check if held item is blacklisted | - -**Examples:** -``` -/cnpc auction blacklist add item minecraft:diamond_sword -/cnpc auction blacklist add item minecraft:diamond* (wildcard) -/cnpc auction blacklist add mod industrialcraft2 -/cnpc auction blacklist add nbt ench -/cnpc auction blacklist remove item minecraft:diamond_sword -/cnpc auction blacklist list item -/cnpc auction blacklist check (checks held item) -``` - ---- - -## 8. Implementation Status - -### Phase 1: Currency System - COMPLETE ✅ -### Phase 2: Trader Enhancements - COMPLETE ✅ -### Phase 3: Auction Core - COMPLETE ✅ -### Phase 4: Auction GUI - COMPLETE ✅ -### Phase 5: Auction Network - COMPLETE ✅ -### Phase 6: Performance & Safety - COMPLETE ✅ - -1. ~~Threading model with ReentrantReadWriteLock~~ -2. ~~Player indices for O(1) lookups~~ -3. ~~20-second update cycle~~ -4. ~~Async saves on CNPC+ thread~~ -5. ~~Race condition prevention~~ -6. ~~Server shutdown handling~~ -7. ~~Own listing view (buttons hidden)~~ -8. ~~Server-side security checks~~ - -### Remaining Work - -- [ ] **GuiManageAuction (Admin GUI)** - Admin interface to view all auctions, cancel listings, manage claims -- [ ] Additional testing - -### Implemented Since Initial Plan - -- [x] **`/auction` Command** - Console/player command with subcommands: - - `/auction list [page]` - View active auctions from command line - - `/auction view ` - View a player's auction activity (listings, bids, claims) - - `/auction open` - Open Auction House GUI without needing an Auctioneer NPC -- [x] **Permission system integration** - Per-player trade slot limits via `customnpcs.auction.trades.X` permissions - - Default: 8 trade slots - - Maximum: 45 (9x5 grid) - - Synced to client when viewing My Trades - - Cached on login for performance -- [x] **Minimum Listing Price** - Configurable minimum starting price (default: 1) -- [x] **Buyout enabled by default** - Buyout toggle is ON by default when creating listings -- [x] **Search by seller** - Filter can now search by item name OR seller name -- [x] **Rebid prevention** - Players cannot rebid on auctions where they're already the highest bidder -- [x] **Buyout price difference** - When buying out an auction you're bidding on, only pay the difference -- [x] **Immediate claim cleanup** - Claims are removed from storage immediately when claimed -- [x] **Listing cleanup** - Ended listings are removed when all related claims are processed -- [x] **Live notifications** - Notifications sent immediately to online players instead of queued -- [x] **Login claim summary** - Shows detailed claim summary on login (X items and Y currency to claim) -- [x] **PlayerTradeData** - Merged currency + claims into single class (shared across profiles) -- [x] **No locking system** - Pure ConcurrentHashMap for better performance -- [x] **30-second intervals** - Combined process/save cycle for simplicity -- [x] **Async offline player claims** - Claims added to offline players via CNPC+ thread -- [x] **Claim migration** - Old claims in auction.dat automatically migrated to PlayerData -- [x] **Item Blacklist System** - Block items by registry name, mod, NBT tag, or wildcard pattern - - Auto-blocks Soulbound and Profile-Slotbound items (checks `RPGCore/Requirements`) - - Per-player bypass via `customnpcs.auction.blacklist.bypass` permission - - Runtime add/remove commands (not persisted to config) - - Check command to test held item - ---- - -## 9. Design Decisions - -| Decision | Choice | Rationale | -|----------|--------|-----------| -| Claims Storage | In PlayerData, not auction.dat | Claims persist with player, reduces auction.dat size, allows offline claim addition | -| Thread Safety | ConcurrentHashMap (no locks) | Minecraft is single-threaded for gameplay; locks add overhead without benefit | -| Vault Integration | Via PlayerCurrencyData | Single point of delegation, reused by Trader & Auction | -| Update Interval | 30 seconds | Performance vs responsiveness tradeoff | -| Player Indices | ConcurrentHashMap + Sets | O(1) lookups, thread-safe | -| Async Saves | CNPC+ Thread | Doesn't block server tick | -| Offline Claims | Load PlayerData async, add claim, save | Claims can be added to offline players without blocking | -| Config Sync | LoginPacket → AuctionClientConfig | Client never accesses server config directly | -| Item Blacklist | Static utility class | Simple, fast checks without instantiation; auto-blocks bound items | -| Bound Item Detection | Check `RPGCore/Requirements` NBT path | Uses AttributeItemUtil constants for consistency | - ---- - -## 10. Future Considerations (Not in 1.11) - -- Category-based filtering (by item type, mod, etc.) -- Auction history/statistics tracking -- Auction house tax sink (currency removed from economy) -- Reserve prices (hidden minimum price) -- Private auctions (invite-only) -- Watchlist/favorites system -- Price history graphs diff --git a/Ability_Beta_Update.md b/Ability_Beta_Update.md new file mode 100644 index 000000000..8733ebc8b --- /dev/null +++ b/Ability_Beta_Update.md @@ -0,0 +1,144 @@ +# CNPC+ 1.11 Ability System Beta + +🟡 **In Testing** + + + +## Features: ⚒️ + +- **Phase-Based Execution:** + +> All abilities follow a Wind-up → Active → Completion flow. Wind-up lets players react, Active deals the effect. + + + +- **Melee Abilities:** + +> - **Slam** - Leap and AOE on impact. +> - **Heavy Hit** - Single powerful strike with bonus knockback. +> - **Cutter** - Slashing cone arc attack. +> - **Shockwave** - AOE burst radiating from the caster. + + + +- **Energy Orbs:** + +> - **Orb** - Homing energy sphere. +> - **Dual Orb** - Two simultaneous homing orbs. +> - **Orb Barrage** - Rapid volley of orbs in sequence. + + + +- **Energy Discs:** + +> - **Disc** - Spinning flat projectile with optional boomerang. +> - **Dual Disc** - Two simultaneous discs. + + + +- **Energy Beams:** + +> - **Beam** - Sustained homing beam from caster to target. +> - **Dual Beam** - Two simultaneous beams. + + + +- **Laser Shot:** + +> Instant-fire projectile with no homing. Pure aim. + + + +- **Projectile:** + +> Standard projectile using classic Minecraft physics. + + + +- **Movement Abilities:** + +> - **Charge** - Rush forward in a line, damaging everything in path. +> - **Dash** - Quick directional movement without damage. +> - **Teleport** - Instant relocation to the target. + + + +- **AOE Abilities:** + +> - **Sweeper** - Wide rotational sweep around the caster. +> - **Vortex** - Pulls entities inward while dealing damage. + + + +- **Telegraph System:** + +> Visual ground indicators during wind-up. Supports Circle, Ring, Line, Cone, and Point shapes with color customization and warning phase transitions. + + + +- **Energy Projectile Customization:** + +> Modular data system for all energy projectiles: Anchor Point, Display Colors, Homing, Combat Stats, and Lifespan. + + + +- **Ability Effects:** + +> Abilities can apply potion effects on hit: Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue. + + + +- **Ability Conditions:** + +> Condition system controlling when abilities can execute based on target state and custom predicates. + + + +- **Interruptible Wind-ups:** + +> Abilities can be interrupted by damage during wind-up, forcing a configurable Dazed recovery state. + + + +- **Movement & Rotation Locking:** + +> Lock caster movement, rotation, or both during Wind-up, Active, or both phases. + + + +- **Animation & Sound Integration:** + +> Wind-up and Active animations with optional duration sync. Custom sound events per phase. + + + +- **Player Abilities:** + +> Players can unlock abilities, select one at a time, and share a universal cooldown. + + + +- **Ability Preview:** + +> Live preview in the ability editor GUI. Test telegraphs, animations, and projectiles on a dummy NPC. + + + +- **Scripting API:** + +> Full event support: Start, Execute, Interrupt, Complete, Hit (modifiable damage/knockback), and Tick events. Start, Execute, and Hit are cancelable. + + + +- **Ability Commands:** + +> `/kam ability list`, `types`, `info`, `delete`, `reload` for managing custom abilities. + + + +**Extras** + +- Global ability presets that update everywhere when edited. +- Weighted ability selection for NPC random usage. +- Configurable min/max range per ability. +- Reusable telegraph presets shared across abilities. diff --git a/Ability_Update.md b/Ability_Update.md new file mode 100644 index 000000000..cf160bc5f --- /dev/null +++ b/Ability_Update.md @@ -0,0 +1,199 @@ +# ⚔️ CustomNPC+ 1.11 - Abilities ⚔️ + +--- + +The **Ability Update** introduces a full combat ability system to CNPC+! Give your NPCs powerful attacks with **visual telegraphs**, launch **energy projectiles** that home in on targets, and let players unlock abilities of their own! + +--- + +## How Abilities Work 🎯 + +Every ability follows a **phase-based execution flow** that gives combat a readable, strategic feel. + +**Phases:** +- **Wind-up** - The ability charges. Telegraphs appear, animations play, and observant players can react +- **Active** - The ability fires. Damage is dealt, projectiles launch, effects apply +- **Dazed** - Optional recovery state if the ability is interrupted during wind-up + +**Core Configuration:** +- **Cooldown** - Time before the ability can be used again +- **Targeting Mode** - Aggro Target, Self, AOE on Self, or AOE on Target +- **Range** - Configurable min and max range for activation +- **Lock Movement** - Lock the caster's movement, rotation, or both during any phase +- **Interruptible** - Allow damage to interrupt wind-up and force a dazed state +- **Weight** - Priority weighting for NPC random ability selection + +> Abilities support both **inline configuration** on individual NPCs and **global presets** that update everywhere when edited. + +--- + +## Melee Abilities 🗡️ + +Close-range attacks that hit hard and punish positioning. + +- **Slam** - Leap toward the target in an arc, dealing AOE damage on impact. Configurable radius, knockback, and leap height +- **Heavy Hit** - A single powerful melee strike with bonus knockback +- **Cutter** - A slashing arc attack in a cone. Configurable angle and reach +- **Shockwave** - An AOE burst radiating outward from the caster + +> All melee abilities support configurable **damage**, **knockback**, and **potion effects** on hit. + +--- + +## Energy Projectiles ✨ + +A brand new projectile system built from the ground up with full visual customization. + +### Orbs + +Homing energy spheres that track their target through the air. + +- **Orb** - A single homing projectile +- **Dual Orb** - Fires two orbs simultaneously +- **Orb Barrage** - Fires a volley of orbs in rapid sequence + +### Discs + +Flat spinning projectiles with optional **boomerang** behavior. + +- **Disc** - A single spinning disc with configurable radius and thickness +- **Dual Disc** - Fires two discs simultaneously + +### Beams + +Sustained energy beams that connect the caster to their target. + +- **Beam** - A homing beam with configurable width and head size. Locks the caster in place during channeling +- **Dual Beam** - Fires two beams simultaneously + +### Laser Shot + +An **instant-fire** projectile with configurable width and speed. No homing — pure aim. + +### Projectile + +A standard projectile using classic Minecraft physics for a more traditional ranged attack. + +### Energy Configuration + +Every energy projectile shares a **modular data system** for deep customization: + +- **Anchor Point** - Choose where the projectile spawns: Right Hand, Left Hand, Front, Center, Chest, or Above Head +- **Display** - Set core color, edge color, glow effect, transparency, and size +- **Homing** - Toggle homing, adjust turn rate and max tracking range +- **Combat** - Damage, knockback, vertical knockback, hit cooldown, and optional AOE splash +- **Lifespan** - Projectile speed, max age, and max travel distance + +--- + +## Movement Abilities 💨 + +Abilities that reposition the caster in combat. + +- **Charge** - Rush forward in a line, damaging all entities in the path. Configurable speed, hit width, and knockback +- **Dash** - A quick directional movement without dealing damage +- **Teleport** - Instantly relocate to the target's position + +> **Charge** locks direction during wind-up, so the telegraph accurately shows the attack path. + +--- + +## AOE Abilities 🌀 + +Area control abilities that dominate space. + +- **Sweeper** - A wide rotational sweep attack around the caster with configurable radius and rotation speed +- **Vortex** - Creates a pulling force that drags nearby entities toward the center while dealing damage + +--- + +## Telegraph System 📍 + +**Telegraphs** are visual ground indicators that warn players before an ability lands. They appear during the wind-up phase and disappear when the ability fires. + +**Shapes:** +- **Circle** - Filled circle with configurable radius +- **Ring** - Donut shape with inner and outer radius +- **Line** - Rectangle along the attack direction +- **Cone** - Fan/wedge shape with configurable angle +- **Point** - Single point indicator + +**Features:** +- **Color Customization** - Set ARGB colors for both the telegraph and its warning phase +- **Warning Phase** - Color shifts in the final ticks before the ability fires +- **Entity Tracking** - Telegraphs can follow a moving entity or stay at a fixed position +- **Smooth Interpolation** - Position updates are interpolated for clean visuals + +> Telegraphs are saved as **reusable presets** and can be shared across multiple abilities. + +--- + +## Animations & Sound 🎬 + +Abilities integrate directly with the animation and sound systems. + +- **Wind-up Animation** - Plays during the charging phase +- **Active Animation** - Plays when the ability fires +- **Animation Sync** - Optionally sync wind-up duration to match animation length exactly +- **Sound Events** - Assign custom sounds to both wind-up and active phases +- **Phase Colors** - Visual color feedback on the caster during wind-up and active + +> Many ability types include **built-in animation names** that work automatically when matching animations exist. + +--- + +## Effects & Conditions ⚡ + +### Potion Effects + +Abilities can apply **potion effects** to any entity they hit. Each effect has configurable type, duration, and amplifier. + +**Available Effects:** +Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue + +### Conditions + +Abilities support a **condition system** that controls when they can be used. Conditions are evaluated before execution and can require specific target states, ranges, or custom predicates. + +--- + +## Player Abilities 🧑 + +Players can unlock and use abilities too! + +- **Unlock System** - Players receive abilities via scripting or commands +- **Ability Selection** - Choose one ability at a time from your unlocked list +- **Universal Cooldown** - Shared cooldown across all player abilities + +--- + +## Scripting API 📜 + +Full scripting support for ability lifecycle events: + +- **StartEvent** *(Cancelable)* - Fired when wind-up begins +- **ExecuteEvent** *(Cancelable)* - Fired when the ability activates +- **InterruptEvent** - Fired when wind-up is interrupted by damage +- **CompleteEvent** - Fired when the ability finishes +- **HitEvent** *(Cancelable)* - Fired on each entity hit. Damage and knockback values can be modified +- **TickEvent** - Fired every tick with current phase and tick count + +> Scripts can cancel, modify damage, and react to every phase of ability execution. + +--- + +## Ability Preview 🔎 + +The ability editor includes a **live preview system**. Test your telegraph shapes, animations, and projectile visuals directly in the GUI on a dummy NPC — no world effects applied. + +--- + +## Ability Commands 💬 + +- `/kam ability list` - List all custom abilities +- `/kam ability types` - List all registered ability types +- `/kam ability info ` - View ability details +- `/kam ability delete ` - Delete a custom ability +- `/kam ability reload` - Reload abilities from disk + +--- diff --git a/Ability_Update_Review.md b/Ability_Update_Review.md deleted file mode 100644 index 2ceb38797..000000000 --- a/Ability_Update_Review.md +++ /dev/null @@ -1,301 +0,0 @@ -# Ability System Review - CustomNPC+ - -A comprehensive technical review of the Ability System identifying bugs, logic issues, incomplete features, and inconsistencies. - ---- - -## Critical Issues - -### 1. Cooldown Uses Mixed Time Systems -**Status:** FIXED -**Files:** -- `Ability.java` - Removed cooldown tracking (cooldownEndTime, startCooldown(), isOnCooldown(), canUse()) -- `DataAbilities.java` - Now sole owner of cooldown management using world time - -**Solution:** Removed all cooldown tracking from `Ability.java`. Cooldowns are now managed exclusively by `DataAbilities` using `world.getTotalWorldTime()` for consistency. - ---- - -### 2. AbilityHeal - Heal Over Time Completely Broken -**Status:** FIXED -**File:** `AbilityHeal.java` - -**Solution:** Refactored to separate ally-finding from healing. The `findAlliesInRadius()` method is now called regardless of `instantHeal` flag, populating the list for HoT to use. Added heal particles during HoT ticks. - ---- - -### 3. AbilityGuard - Counter Integration Missing -**Status:** FIXED -**Files:** -- `DataAbilities.java:onDamage()` - Added integration to call `AbilityGuard.onDamageTaken()` -- `DataAbilities.java:getGuardDamageReduction()` - Added helper method for damage reduction - -**Solution:** `DataAbilities.onDamage()` now checks if current ability is an `AbilityGuard` and calls `onDamageTaken()` when the NPC is hit while guarding. - ---- - -## High Priority Issues - -### 4. knockbackUp Stored But Never Applied -**Status:** FIXED -**File:** `Ability.java` - -**Solution:** Updated `applyNpcKnockback()` to accept a `knockbackUp` parameter and use it instead of hardcoded `0.1D`. Both `applyAbilityDamage()` and `applyAbilityDamageWithDirection()` now pass the knockbackUp value from the HitEvent. - ---- - -### 5. Targeting Modes Not Implemented -**Status:** FIXED (Removed) -**File:** `TargetingMode.java` - -**Solution:** Removed the unused targeting modes (`RANDOM_ENEMY`, `LOWEST_HP`, `HIGHEST_THREAT`) from the enum. Only the implemented modes remain: `AGGRO_TARGET`, `SELF`, `AOE_SELF`, `AOE_TARGET`. - ---- - -### 6. Damage Source Inconsistency -**Status:** FIXED -**File:** `Ability.java` - -**Solution:** Standardized both `applyAbilityDamage()` and `applyAbilityDamageWithDirection()` to use `NpcDamageSource("mob", npc)` for consistent damage source handling. - ---- - -## Incomplete Features - -### 7. AbilityProjectile - No Actual Projectile -**Status:** CONFIRMED - INCOMPLETE -**File:** `AbilityProjectile.java:88` - -```java -// TODO: Use custom EntityAbilityProjectile for actual tracking -applyAbilityDamageWithDirection(npc, target, damage, knockback, dx, dz); -``` - -**Current behavior:** -- `speed`, `homing`, `homingStrength` fields exist but are unused -- No projectile entity is spawned -- Damage is instant, just with particle cosmetics - ---- - -### 8. AbilityOrb - No Visual Orb Rendering -**Status:** CONFIRMED - INCOMPLETE -**File:** `AbilityOrb.java:117-179` - -**Problem:** The orb tracks position (`orbX`, `orbY`, `orbZ`) with runtime getters but nothing renders it client-side. Players only see particle effects on hit, not the flying orb itself. - ---- - -### 9. AbilityBeam - No Visual Beam Rendering -**Status:** CONFIRMED - INCOMPLETE -**File:** `AbilityBeam.java:213-220` - -**Problem:** Only spawns flame particles along the path. No actual beam entity or proper beam visual. The `lockOnTarget` telegraph during active phase isn't visually communicated. - ---- - -## Medium Priority Issues - -### 10. Hazard/Trap Telegraph Offset Mismatch -**Status:** CONFIRMED -**Files:** -- `AbilityHazard.java:119-147, 201-248` -- `AbilityTrap.java:109-138, 166-205` - -**Problem:** Telegraph is created at target position, but actual effect applies random offset: - -```java -// createTelegraph() - No offset applied, shows at target position - -// onExecute() - Random offset applied AFTER telegraph locks -double[] pos = calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ()); -zoneX = pos[0]; // Actual effect position differs from telegraph -``` - -**Impact:** Players see telegraph at one location, damage happens elsewhere. Misleading visual feedback. - -**Fix:** Either apply offset during telegraph creation, or update telegraph position in `onExecute()`. - ---- - -### 11. AbilityCharge Telegraph Direction Timing -**Status:** CONFIRMED - MINOR -**File:** `AbilityCharge.java:91, 254-286` - -**Problem:** Telegraph created at tick 0, direction locked at tick 1: - -```java -// Telegraph created during setup (tick 0) with current target direction -// Line 91: Direction locked at tick 1 -if (tick == 1) { - lockChargeDirection(npc, target); -} -``` - -**Impact:** If target moves between tick 0-1, telegraph direction won't match actual charge. - ---- - -### 12. AbilitySlam - activeTicks May End Before Landing -**Status:** CONFIRMED - MINOR -**File:** `AbilitySlam.java:52-53, 230-250` - -**Problem:** `activeTicks = 60` is fixed, but if NPC takes longer to land, ability transitions to RECOVERY without `onLanding()` being called. - -**Secondary issue:** If NPC lands early (tick 15), active phase continues until tick 60 doing nothing - wasted ticks. - ---- - -### 13. FOLLOW Mode Telegraph Not Updated -**Status:** CONFIRMED -**Files:** `AbilityHazard.java:139-146`, `AbilityVortex.java` - -**Problem:** For `FOLLOW_TARGET` mode, telegraph locks position on execute, but the actual hazard zone follows the target. Visual mismatch between warning and danger. - ---- - -## Redundancies - -### 14. Duplicate findGroundLevel() Methods -**Status:** FIXED -**Files:** -- `Ability.java` - Made `findGroundLevel()` public static -- `TelegraphInstance.java` - Now uses `Ability.findGroundLevel()` - ---- - -### 15. Duplicate calculateOffsetPosition() Methods -**Status:** FIXED -**Files:** -- `Ability.java` - Added shared static `calculateOffsetPosition()` method -- `AbilityTrap.java` - Removed duplicate, uses `Ability.calculateOffsetPosition()` -- `AbilityHazard.java` - Removed duplicate, uses `Ability.calculateOffsetPosition()` - ---- - -### 16. Unused applyKnockback in AbilityOrb -**Status:** FIXED -**File:** `AbilityOrb.java` - -Removed the unused `applyKnockback()` method. - ---- - -### 17. Duplicate Reset/Interrupt Cleanup -**Status:** NOT FIXED (Low Priority) -**Multiple ability files** - -Most abilities override both `reset()` and `onInterrupt()` with duplicate cleanup code. Pattern should have `onInterrupt()` call `reset()` or use shared cleanup method. - ---- - -## Minor Issues & Inconsistencies - -### 18. Field Naming Confusion -- `AbilityHazard`: `damagePerSecond` with `damageInterval` - name suggests per-second but applied every N ticks -- `AbilityCharge`: `hitWidth` stored as `hitRadius` in older NBT (backward compat exists) - -### 19. AbilityVortex Entity Lookup Performance -**File:** `AbilityVortex.java:201-212` - -Iterates through ALL loaded entities every tick to find pulled entities by UUID. Should cache entity references or use entity IDs. - -### 20. Telegraph Yaw Rotation -**File:** `TelegraphRenderer.java:95` - -Uses `GL11.glRotatef(-instance.getYaw(), 0, 1, 0)` - negative yaw. Should verify this matches Minecraft's yaw conventions. - -### 21. Missing Null Checks -Various locations where `target` could be null but is used without defensive checks: -- `AbilityProjectile.java:73` -- `AbilityOrb.java:138-171` - ---- - -## Missing Features (Enhancement Requests) - -These are not bugs but notable missing functionality: - -1. **No Ability Chaining/Combo System** - No way to trigger abilities from other abilities -2. **No Cooldown Reduction on Hit** - Can't reduce cooldowns based on successful hits -3. **No Multi-Target Hit Limit** - AOE abilities hit unlimited targets (unlike Vortex's `maxTargets`) -4. **No Damage Type Configuration** - All abilities use mob/melee damage, no magic/fire/etc options -5. **No Target Validation During Execution** - If target dies/despawns mid-ability, behavior varies - ---- - -## Priority Summary - -| Priority | Issue | Status | -|----------|-------|--------| -| **CRITICAL** | Cooldown time system mismatch | FIXED | -| **CRITICAL** | AbilityHeal HoT broken | FIXED | -| **CRITICAL** | AbilityGuard counter not integrated | FIXED | -| **HIGH** | knockbackUp ignored | FIXED | -| **HIGH** | Targeting modes unimplemented | FIXED (Removed) | -| **HIGH** | Damage source inconsistency | FIXED | -| **MEDIUM** | Projectile/Orb/Beam no visuals | Not Fixed | -| **MEDIUM** | Hazard/Trap telegraph offset | Not Fixed | -| **LOW** | Charge telegraph timing | Not Fixed | -| **LOW** | Slam activeTicks timing | Not Fixed | -| **LOW** | Code redundancies | FIXED | - ---- - -## Remaining Issues - -The following issues were not addressed in this fix round: - -1. **Projectile/Orb/Beam Visual Rendering** - These abilities still only use particles, no actual entity rendering -2. **Hazard/Trap Telegraph Offset Mismatch** - Telegraph shows at target, effect spawns with offset -3. **Charge Telegraph Direction Timing** - Minor visual mismatch between tick 0-1 -4. **Slam activeTicks Timing** - Fixed at 60 ticks regardless of landing time - ---- - -## Changes Made - -### Ability.java -- Removed `cooldownEndTime` transient field -- Removed `startCooldown()`, `isOnCooldown()`, `canUse()` methods (cooldown managed by DataAbilities) -- Updated `tick()` to not call startCooldown (DataAbilities handles it) -- Updated `reset()` to not reset cooldownEndTime -- Made `findGroundLevel()` public static for shared use -- Added static `calculateOffsetPosition()` utility method -- Fixed `applyNpcKnockback()` to accept and use knockbackUp parameter -- Standardized damage source to `NpcDamageSource("mob", npc)` in both damage methods -- Removed deprecated getters/setters (telegraphColor, castSound, animationId) - -### IAbility.java (API) -- Removed `isOnCooldown()` method from interface - -### DataAbilities.java -- Added AbilityGuard import -- Added guard counter integration in `onDamage()` -- Added `getGuardDamageReduction()` helper method -- Removed deprecated `isMovementBlocked()` method -- Updated knockbackUp javadoc (no longer deprecated) - -### CombatHandler.java -- Renamed `isMovementBlocked()` to `isAbilityControllingMovement()` - -### TargetingMode.java -- Removed unused modes: `RANDOM_ENEMY`, `LOWEST_HP`, `HIGHEST_THREAT` - -### AbilityHeal.java -- Fixed HoT by separating `findAlliesInRadius()` from healing logic -- Allies are now found in `onExecute()` regardless of instantHeal flag -- Added heal particles during HoT ticks - -### AbilityHazard.java -- Removed duplicate `calculateOffsetPosition()`, uses `Ability.calculateOffsetPosition()` -- Removed deprecated `getDamagePerTick()`/`setDamagePerTick()` methods - -### AbilityTrap.java -- Removed duplicate `calculateOffsetPosition()`, uses `Ability.calculateOffsetPosition()` - -### AbilityOrb.java -- Removed unused `applyKnockback()` method - -### TelegraphInstance.java -- Removed duplicate `findGroundLevel()`, uses `Ability.findGroundLevel()` diff --git a/Auction_Beta_Update.md b/Auction_Beta_Update.md new file mode 100644 index 000000000..8b382b4af --- /dev/null +++ b/Auction_Beta_Update.md @@ -0,0 +1,57 @@ +# CNPC+ 1.11 Beta - Market Update + +🟡 **In Testing** + +## Features: ⚒️ + +- **Built-in Currency System:** +> Fully configurable economy currency used across all Market features. Profile persistent across character slots with Vault support for Bukkit-compatible plugins. + +- **Auction House:** +> Global player marketplace for listing items, bidding, and instant buyouts. Auctions last 24 hours by default. + +- **Auction Bidding & Snipe Protection:** +> Competitive bidding with a 5% minimum bid increment. Snipe Protection extends auctions on last-second bids. Outbid players are automatically refunded. + +- **Buyout System:** +> Instant purchase at the seller's Buyout Price. Highest bidder only pays the difference between their bid and the buyout. + +- **My Trades:** +> Single screen for managing Active Listings, Active Bids, and Pending Claims. Players can cancel listings with a 10% penalty if bids exist. + +- **Auction Notifications:** +> Real-time notifications for sales, outbids, and wins. Offline players receive a claim summary on login. + +- **Trade Slots:** +> Limited slots (default 8, max 45) shared across listings, bids, and claims. Configurable via permissions. + +- **Claim Expiration:** +> Uncollected claims expire after 20 days. + +- **Item Blacklist:** +> Block items by registry name, wildcard pattern, mod, or NBT tag. Soulbound and Profile-Slotbound items are always blocked automatically. + +- **Listing Fee & Sales Tax:** +> Configurable listing fee charged on creation and sales tax taken from successful sales. + +- **Search & Sorting:** +> Search by item name or seller. Sort by newest, ending soon, price, or most bids. + +- **Trader Stock System:** +> Limited stock with Global or Per-Player modes. Restock timers for MC Daily/Weekly, RL Daily/Weekly, or Custom intervals. + +- **Trader Currency Trades:** +> Trades can require currency on top of item costs. + +- **Auctioneer NPC Role:** +> New role that opens the Auction House on interaction. No configuration needed. + +- **Auction Commands:** +> `/kam auction open` for players. Admin commands for listing view and player activity inspection. + +**Extras** + +- Auction logging for server admins (tracks creates, bids, buyouts, sales, expirations, cancellations, claims). +- Lifetime currency tracking per player (total earned and spent). +- Configurable starting balance and max balance cap. +- Blacklist bypass permission for admins. diff --git a/Auction_Update.md b/Auction_Update.md index ae839832f..a04cc12e9 100644 --- a/Auction_Update.md +++ b/Auction_Update.md @@ -10,9 +10,10 @@ The **Market Update** brings a complete economy system to CNPC+! Create bustling CNPC+ now has a **built-in currency** used across all Market features! -- **Fully Configurable** - Name it Coins, Gold, Credits, whatever fits your world +- **Fully Configurable** - Name it Coins, Gold, Credits, whatever fits your world. Set a starting balance and max balance cap to shape your economy - **Profile Persistent** - Currency carries across all your character slots -- **Vault Support** - CNPC+ integrates seamlessly with Bukkit-compatible economy plugins if Vault is installed +- **Vault Support** - Integrates seamlessly with Bukkit-compatible economy plugins if Vault is installed. Falls back to built-in currency otherwise +- **Lifetime Tracking** - Tracks total earned and spent per player > Full Scripting API support for currency operations on players. @@ -20,17 +21,17 @@ CNPC+ now has a **built-in currency** used across all Market features! ## Auction House 🏛️ -A **global player marketplace** where players can list items, bid against each other, and purchase instantly! +A **global player marketplace** where players can list items, bid against each other, and purchase instantly! Search for items by name or seller, and sort by newest, ending soon, price, or most bids. ### Selling -List any item with a **Starting Price** for competitive bidding. Set an optional **Buyout Price** for players who want to skip the wait and buy immediately. +List any item with a **Starting Price** for competitive bidding. Set an optional **Buyout Price** for players who want to skip the wait and buy immediately. Auctions last **24 hours** by default. > A configurable **Listing Fee** is charged when creating auctions, and a **Sales Tax** is taken from successful sales. ### Bidding -Compete for items by placing bids! **Snipe Protection** extends auctions when last-second bids come in, giving everyone a fair shot. If you get outbid, your currency is **automatically refunded**. +Compete for items by placing bids! Each bid must be at least **5%** higher than the current bid. **Snipe Protection** extends auctions when last-second bids come in, giving everyone a fair shot. If you get outbid, your currency is **automatically refunded**. ### Buyout @@ -44,7 +45,9 @@ One screen to manage all your auction activity: - **Active Bids** - Auctions you're competing in - **Ready to Claim** - Won items and currency waiting for pickup -> Players can **cancel** their own listings. Items are returned as a claim. +Players can **cancel** their own listings -- items are returned as a claim. If there are active bids on the listing, a **10% cancellation penalty** is charged. + +> Claims expire after **20 days**. Make sure to collect your items and currency before they're gone! ### Notifications @@ -52,7 +55,7 @@ Get notified immediately when your item sells, when you're outbid, or when you w ### Trade Slots -Each player has a limited number of **Trade Slots** (default 8). Trade Slots are shared between Active Listings, Active Bids, and Pending Claims. +Every player gets a limited number of **Trade Slots** (default 8). Slots are shared across Active Listings, Active Bids, **and** Pending Claims -- so uncollected claims take up space. Pick up your claims to free slots for new listings and bids! > Server owners can grant players more slots via permissions up to a maximum of 45. @@ -68,14 +71,9 @@ Server owners have full control over what items can be listed on the Auction Hou - **Mod** - Block all items from a specific mod - **NBT Tag** - Block items containing certain NBT data -> **Soulbound** and **Profile-Slotbound** items are always blocked automatically. Bound items cannot be traded! +> **Soulbound** and **Profile-Slotbound** items are always blocked automatically, regardless of blacklist settings. Bound items cannot be traded! -**Blacklist Commands:** -- `/kam auction blacklist add ` - Add entry -- `/kam auction blacklist remove ` - Remove entry -- `/kam auction blacklist list` - View all blacklisted entries -- `/kam auction blacklist check` - Check if your held item is blacklisted -- `/kam auction blacklist reload` - Reload from config +Manage the blacklist in-game with `/kam auction blacklist` commands, or configure it directly in the config file. --- @@ -94,14 +92,10 @@ Traders now support **limited stock** with automatic restocking! - **RL Daily / Weekly** - Restock based on real-life time - **Custom** - Set your own interval in MC ticks or real-time -**Visual Feedback:** -- Stock count displayed next to each trade -- **Out of Stock** overlay when unavailable -- Live **countdown timer** until next restock +Stock counts, out-of-stock status, and restock timers are all visible directly in the trade interface. > Admins can manually reset stock or cooldowns via the Trader GUI. - ### Currency Trades Trades can now require **currency on top of items**. Combine material costs with coin costs for balanced economy progression! @@ -110,10 +104,9 @@ Trades can now require **currency on top of items**. Combine material costs with ## Auctioneer Role 🧑‍💼 -New NPC role for the Auction House! Set the role on any NPC and players can access the full Auction House by interacting with them. -> No configuration needed +New NPC role for the Auction House! Set the role on any NPC and players can access the full Auction House by interacting with them -- no extra configuration needed. The role respects the global Auction Enabled setting. -### Auction Command +### Auction Commands Players can also access the Auction House via command: @@ -123,5 +116,6 @@ Players can also access the Auction House via command: - `/kam auction list [page]` - View active auctions in chat - `/kam auction view ` - View a player's auction activity ---- +> Server owners can enable **auction logging** to track all auction activity (creates, bids, buyouts, sales, expirations, cancellations, and claims). +--- diff --git a/build.gradle b/build.gradle index de4d414d0..7421f7cf7 100644 --- a/build.gradle +++ b/build.gradle @@ -31,6 +31,21 @@ tasks.create('buildNoMixin', Exec) { commandLine gradleWrapper, 'build', '-Pnomixin' } +// No Nashorn Run Tasks +tasks.create('runClientNoNashorn', Exec) { + description 'Runs the client without Nashorn' + group 'CustomNPC+' + workingDir project.rootDir + commandLine gradleWrapper, 'runClient', '-PnoNashorn' +} + +tasks.create('runServerNoNashorn', Exec) { + description 'Runs the server without Nashorn' + group 'CustomNPC+' + workingDir project.rootDir + commandLine gradleWrapper, 'runServer', '-PnoNashorn' +} + sourceSets.main.java { def apiDir = file('src/api/java') diff --git a/dependencies.gradle b/dependencies.gradle index 5f8f40b1e..486ef7430 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -36,7 +36,12 @@ def embedMixin = !project.hasProperty("nomixin"); dependencies { runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.5.4-GTNH:dev") - runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946") + if (!project.hasProperty("noNashorn")) { + runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946") + } + +// compileOnly(files("./tools/bukkit-api/spigot-api-ONLY.jar")) +// compileOnly(files("./tools/bukkit-api/Vault-1.4.1.jar")) shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar")) annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar")) diff --git a/gradle-plugins b/gradle-plugins index bfa9565fc..f1c82c10c 160000 --- a/gradle-plugins +++ b/gradle-plugins @@ -1 +1 @@ -Subproject commit bfa9565fce3110adb8fb4e9fd1a52bafdd7d35e6 +Subproject commit f1c82c10c8c92eaaf55044cf931da5e1c7a2668f diff --git a/src/api b/src/api index db6a68e43..fd4c77d01 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit db6a68e43073b2828ec05a3c2ede660453c4544e +Subproject commit fd4c77d015add1f6f3012a1681561b2774f2f997 diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java index 20486d70e..8cb8cdaad 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java @@ -43,7 +43,16 @@ public class RenderAbilityDisc extends RenderAbilityProjectile { GL11.glPushMatrix(); GL11.glScalef(scale, scale, scale); - // Apply ONLY Y-axis rotation for flat spin + if (disc.isVertical()) { + // Vertical mode: thin edge faces direction of travel (like a saw blade) + // 1. Spin in local space (Y-axis) + // 2. Tilt 90° to stand up (X-axis) + // 3. Orient to face travel direction (Y-axis world yaw) + GL11.glRotatef(disc.getTravelYaw(), 0.0f, 1.0f, 0.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + } + + // Apply Y-axis rotation for spin GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f); // Inner scale defines the core size diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java index bf4df79eb..e70e5c6ba 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java @@ -3,6 +3,7 @@ package kamkeel.npcs.client.renderer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer; +import kamkeel.npcs.entity.EntityAbilityBeam; import kamkeel.npcs.entity.EntityAbilityLaser; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; @@ -20,11 +21,14 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) { EntityAbilityLaser laser = (EntityAbilityLaser) entity; - // Don't render if length is 0 - if (laser.getCurrentLength() <= 0) return; - setupRenderState(); + if (laser.isCharging()) { + renderChargingOrb(laser, x, y, z, partialTicks); + restoreRenderState(); + return; + } + // Get laser parameters double startX = laser.getStartX(); double startY = laser.getStartY(); @@ -123,6 +127,55 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { restoreRenderState(); } + private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks) { + float headSize = laser.getLaserWidth() * 1.5f; + float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks); + float size = headSize * chargeProgress; + + if (size <= 0.01f) return; + + int innerColor = laser.getInnerColor(); + int outerColor = laser.getOuterColor(); + + GL11.glPushMatrix(); + GL11.glTranslated(x, y, z); + + // Pulsing effect + float pulseTime = laser.ticksExisted + partialTicks; + float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f; + float scale = size * (1.0f + scaleModifier); + + // Render lightning during charging if enabled + if (laser.hasLightningEffect()) { + renderAttachedLightning(laser, scale); + } + + GL11.glPushMatrix(); + GL11.glScalef(scale, scale, scale); + + // Inner scale defines the core size + float innerScale = 0.6f; + + // Render outer glow only if enabled + if (laser.isOuterColorEnabled()) { + float outerScale = innerScale + laser.getOuterColorWidth(); + float outerAlpha = laser.getOuterColorAlpha(); + GL11.glDepthMask(false); + GL11.glPushMatrix(); + GL11.glScalef(outerScale, outerScale, outerScale); + renderCube(outerColor, outerAlpha, 0.5f); + GL11.glPopMatrix(); + GL11.glDepthMask(true); + } + + // Render inner core + GL11.glScalef(innerScale, innerScale, innerScale); + renderCube(innerColor, 1.0f, 0.5f); + + GL11.glPopMatrix(); + GL11.glPopMatrix(); + } + /** * Render lightning effects along the laser beam at multiple points. */ @@ -161,6 +214,22 @@ public class RenderAbilityLaser extends RenderAbilityProjectile { GL11.glPopMatrix(); } + + private void renderAttachedLightning(EntityAbilityLaser laser, float headScale) { + AttachedLightningRenderer.LightningState state = getLightningState(laser); + + float density = laser.getLightningDensity(); + // Lightning radius extends outward from inner surface (innerScale = 0.6) + float innerRadius = 0.6f * headScale * 0.5f; + float radius = innerRadius + laser.getLightningRadius() * headScale; + int outerColor = laser.getOuterColor(); + int innerColor = laser.getInnerColor(); + int fadeTime = laser.getLightningFadeTime(); + + state.update(density, radius, outerColor, innerColor, fadeTime); + state.render(); + } + /** * Get or create the main lightning state for the laser. */ diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java index e2e6f8234..048b3642f 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java @@ -56,7 +56,7 @@ public class RenderAbilityOrb extends RenderAbilityProjectile { GL11.glDepthMask(false); GL11.glPushMatrix(); GL11.glScalef(outerScale, outerScale, outerScale); - renderCube(orb.getOuterColor(), 0.5f, 0.5f); + renderCube(orb.getOuterColor(), orb.getOuterColorAlpha(), 0.5f); GL11.glPopMatrix(); GL11.glDepthMask(true); } diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java index cce9bbe58..96e8e7b08 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java @@ -31,6 +31,7 @@ public abstract class RenderAbilityProjectile extends Render { */ protected void setupRenderState() { GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_ALPHA_TEST); @@ -48,9 +49,7 @@ public abstract class RenderAbilityProjectile extends Render { * Restore GL state after rendering. */ protected void restoreRenderState() { - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glPopAttrib(); GL11.glPopMatrix(); } diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java index 4fa28cda8..d68c4037b 100644 --- a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java +++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java @@ -88,17 +88,14 @@ public class AttachedLightningRenderer { /** * Render all active arcs in local space. * Call this after glTranslated to entity position. + * Note: Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). This avoids nesting + * glPushAttrib calls which can overflow the GL attrib stack (depth 16) when + * other mods also push attribs during entity rendering. */ public void render() { if (arcs.isEmpty()) return; - // Setup GL state - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); Tessellator tess = Tessellator.instance; @@ -114,7 +111,6 @@ public class AttachedLightningRenderer { } GL11.glDepthMask(true); - GL11.glPopAttrib(); } public int getArcCount() { @@ -239,6 +235,8 @@ public class AttachedLightningRenderer { /** * Render a single instant lightning arc (no fading, drawn this frame only). + * Expects the caller to have already set up GL state (disabled textures, + * disabled lighting, disabled culling, enabled blending). */ public static void renderInstantArc(float radius, int outerColor, int innerColor) { double theta = rand.nextDouble() * Math.PI * 2; @@ -254,12 +252,6 @@ public class AttachedLightningRenderer { List points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement); - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDepthMask(false); Tessellator tess = Tessellator.instance; @@ -267,7 +259,6 @@ public class AttachedLightningRenderer { renderBoltPath(tess, points, innerColor, 0.012f, 0.7f); GL11.glDepthMask(true); - GL11.glPopAttrib(); } /** diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java index d5b9420cc..004274fc3 100644 --- a/src/main/java/kamkeel/npcs/command/AbilityCommand.java +++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java @@ -2,7 +2,12 @@ package kamkeel.npcs.command; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.AbilityController; +import kamkeel.npcs.controllers.data.ability.UserType; import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayerMP; +import noppes.npcs.NoppesUtilServer; +import noppes.npcs.controllers.PlayerDataController; +import noppes.npcs.controllers.data.PlayerData; import java.util.ArrayList; import java.util.Collections; @@ -122,5 +127,192 @@ public class AbilityCommand extends CommandKamkeelBase { } sendResult(sender, " Range: \u00A7e" + ability.getMinRange() + " - " + ability.getMaxRange()); sendResult(sender, " Telegraph: \u00A7e" + (ability.isShowTelegraph() ? "Yes" : "No")); + sendResult(sender, " Allowed By: \u00A7e" + ability.getAllowedBy().name()); + } + + @SubCommand( + desc = "List all built-in abilities available for players" + ) + public void prebuilts(ICommandSender sender, String[] args) { + Set names = AbilityController.Instance.getAbilityNames(); + if (names.isEmpty()) { + sendResult(sender, "No built-in abilities found."); + return; + } + + List playerAbilities = new ArrayList<>(); + for (String name : names) { + Ability ability = AbilityController.Instance.getAbility(name); + if (ability != null && ability.getAllowedBy().allowsPlayer()) { + playerAbilities.add(name); + } + } + + if (playerAbilities.isEmpty()) { + sendResult(sender, "No player-usable built-in abilities found."); + return; + } + + Collections.sort(playerAbilities); + sendResult(sender, "Built-in Player Abilities (" + playerAbilities.size() + "):"); + for (String name : playerAbilities) { + Ability ability = AbilityController.Instance.getAbility(name); + String userType = ability.getAllowedBy() == UserType.PLAYER_ONLY ? "\u00A7d[PLAYER]" : "\u00A7a[BOTH]"; + sendResult(sender, " - \u00A7b" + name + " " + userType); + } + } + + @SubCommand( + desc = "Unlock an ability for a player", + usage = " " + ) + public void unlock(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability unlock "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + // Resolve ability + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + if (ability == null) { + sendError(sender, "Ability not found: " + abilityKey); + return; + } + + // Use the ability's canonical ID for storage (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId(); + if (canonicalKey == null || canonicalKey.isEmpty()) { + canonicalKey = abilityKey; // Fallback to user-provided key + } + String displayName = ability.getName() != null ? ability.getName() : canonicalKey; + + // Check if ability allows players + if (!ability.getAllowedBy().allowsPlayer()) { + sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players."); + return; + } + + // Get player data and unlock + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player already has ability: " + displayName); + return; + } + + data.abilityData.unlockAbility(canonicalKey); + sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName); + } + + @SubCommand( + desc = "Lock (revoke) an ability from a player", + usage = " " + ) + public void lock(ICommandSender sender, String[] args) { + if (args.length < 2) { + sendError(sender, "Usage: /kam ability lock "); + return; + } + + String playerName = args[0]; + String abilityKey = joinArgs(args, 1); + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + // Resolve ability to get canonical key + Ability ability = AbilityController.Instance.resolveAbility(abilityKey); + String canonicalKey = abilityKey; + String displayName = abilityKey; + if (ability != null) { + canonicalKey = ability.getId() != null ? ability.getId() : abilityKey; + displayName = ability.getName() != null ? ability.getName() : canonicalKey; + } + + // Get player data and lock + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + if (!data.abilityData.hasUnlockedAbility(canonicalKey)) { + sendError(sender, "Player doesn't have ability: " + displayName); + return; + } + + data.abilityData.lockAbility(canonicalKey); + sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName); + } + + @SubCommand( + desc = "List abilities unlocked for a player", + usage = "" + ) + public void player(ICommandSender sender, String[] args) { + if (args.length < 1) { + sendError(sender, "Usage: /kam ability player "); + return; + } + + String playerName = args[0]; + + // Find player + EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName); + if (player == null) { + sendError(sender, "Player not found: " + playerName); + return; + } + + PlayerData data = PlayerDataController.Instance.getPlayerData(player); + String[] abilityKeys = data.abilityData.getUnlockedAbilities(); + + if (abilityKeys.length == 0) { + sendResult(sender, "Player \u00A7a" + playerName + "\u00A77 has no unlocked abilities."); + return; + } + + sendResult(sender, "Abilities for \u00A7a" + playerName + "\u00A77 (" + abilityKeys.length + "):"); + int selected = data.abilityData.getSelectedIndex(); + for (int i = 0; i < abilityKeys.length; i++) { + String key = abilityKeys[i]; + Ability ability = AbilityController.Instance.resolveAbility(key); + String displayName = ability != null && ability.getName() != null ? ability.getName() : key; + String prefix = (i == selected) ? "\u00A7e> " : " "; + // Show display name and key if different + if (!displayName.equals(key)) { + sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]"); + } else { + sendResult(sender, prefix + "\u00A7b" + displayName); + } + } + } + + private String joinArgs(String[] args, int startIndex) { + StringBuilder sb = new StringBuilder(); + for (int i = startIndex; i < args.length; i++) { + if (i > startIndex) sb.append(" "); + sb.append(args[i]); + } + return sb.toString(); + } + + /** + * Get list of player-usable ability keys (for tab completion). + * Uses registry keys for built-in abilities (no spaces) and UUIDs for custom. + * Used by CommandKamkeel for usage token. + */ + public static List getPlayerAbilityNames() { + List keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys()); + Collections.sort(keys); + return keys; } } diff --git a/src/main/java/kamkeel/npcs/command/CloneCommand.java b/src/main/java/kamkeel/npcs/command/CloneCommand.java index 027ff228e..312293ca5 100644 --- a/src/main/java/kamkeel/npcs/command/CloneCommand.java +++ b/src/main/java/kamkeel/npcs/command/CloneCommand.java @@ -13,6 +13,7 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import noppes.npcs.controllers.ServerCloneController; +import noppes.npcs.controllers.data.CloneFolder; import noppes.npcs.entity.EntityNPCInterface; import java.util.List; @@ -35,20 +36,24 @@ public class CloneCommand extends CommandKamkeelBase { @SubCommand( desc = "Add NPC(s) to clone storage", - usage = " [clonedname]", + usage = " [clonedname]", permission = 4 ) public void add(ICommandSender sender, String[] args) { - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { + if (tab < 1 || tab > 15) { sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } int x = sender.getPlayerCoordinates().posX; @@ -64,32 +69,47 @@ public class CloneCommand extends CommandKamkeelBase { NBTTagCompound compound = new NBTTagCompound(); if (!npc.writeToNBTOptional(compound)) return; - ServerCloneController.Instance.addClone(compound, name, tab); - sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab)); + if (folder != null) { + ServerCloneController.Instance.addClone(compound, name, folder); + sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Folder \u00A7b%s\u00A77", name, folder)); + } else { + ServerCloneController.Instance.addClone(compound, name, tab); + sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab)); + } } } } @SubCommand( desc = "List NPC from clone storage", - usage = "", + usage = "", permission = 2 ) public void list(ICommandSender sender, String[] args) { sendMessage(sender, "--- Stored NPCs --- (server side)"); - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { + if (tab < 1 || tab > 15) { sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } - for (String name : ServerCloneController.Instance.getClones(tab)) { + List clones; + if (folder != null) { + clones = ServerCloneController.Instance.getClones(folder); + } else { + clones = ServerCloneController.Instance.getClones(tab); + } + for (String name : clones) { sendMessage(sender, name); } sendMessage(sender, "------------------------------------"); @@ -97,59 +117,75 @@ public class CloneCommand extends CommandKamkeelBase { @SubCommand( desc = "Remove NPC from clone storage", - usage = " ", + usage = " ", permission = 4 ) public void del(ICommandSender sender, String[] args) throws CommandException { String nametodel = args[0]; - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { - sendError(sender, String.format("Tab must be within 1-15")); + if (tab < 1 || tab > 15) { + sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; - } - - boolean deleted = false; - for (String name : ServerCloneController.Instance.getClones(tab)) { - if (nametodel.equalsIgnoreCase(name)) { - ServerCloneController.Instance.removeClone(name, tab); - deleted = true; - break; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; } } - if (!ServerCloneController.Instance.removeClone(nametodel, tab)) { + + boolean success; + if (folder != null) { + success = ServerCloneController.Instance.removeClone(nametodel, folder); + } else { + success = ServerCloneController.Instance.removeClone(nametodel, tab); + } + + if (!success) { sendError(sender, String.format("NPC '%s' was not found", nametodel)); } else { - sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab)); + if (folder != null) { + sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Folder \u00A7b%s\u00A77", nametodel, folder)); + } else { + sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab)); + } } } @SubCommand( desc = "Spawn cloned NPC", - usage = " [[world:]x,y,z]] [newname]", + usage = " [[world:]x,y,z]] [newname]", permission = 2 ) public void spawn(ICommandSender sender, String[] args) throws CommandException { String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { - sendError(sender, String.format("Tab must be within 1-15")); + if (tab < 1 || tab > 15) { + sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } String newname = null; - NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + NBTTagCompound compound; + if (folder != null) { + compound = ServerCloneController.Instance.getCloneData(sender, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + } if (compound == null) { sendError(sender, "Unknown npc"); return; @@ -211,22 +247,26 @@ public class CloneCommand extends CommandKamkeelBase { } @SubCommand( - desc = "Spawn cloned NPC", - usage = " [[world:]x,y,z]] [newname]", + desc = "Spawn cloned NPC in a grid", + usage = " [[world:]x,y,z]] [newname]", permission = 2 ) public void grid(ICommandSender sender, String[] args) throws CommandException { String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space - int tab = 0; + int tab = -1; + String folder = null; try { tab = Integer.parseInt(args[1]); - if (tab < 0 || tab > 15) { - sendError(sender, String.format("Tab must be within 1-15")); + if (tab < 1 || tab > 15) { + sendError(sender, "Tab must be within 1-15"); return; } } catch (NumberFormatException ex) { - sendError(sender, String.format("Tab is not a number: %s", args[1])); - return; + folder = args[1]; + if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) { + sendError(sender, String.format("Unknown folder: %s", folder)); + return; + } } int width, height; @@ -238,9 +278,13 @@ public class CloneCommand extends CommandKamkeelBase { return; } - String newname = null; - NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + NBTTagCompound compound; + if (folder != null) { + compound = ServerCloneController.Instance.getCloneData(sender, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(sender, name, tab); + } if (compound == null) { sendError(sender, "Unknown npc"); return; @@ -317,6 +361,163 @@ public class CloneCommand extends CommandKamkeelBase { return; } + @SubCommand( + desc = "List all custom clone folders", + usage = "", + permission = 2 + ) + public void listfolders(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + sendMessage(sender, "--- Clone Folders ---"); + for (CloneFolder f : ServerCloneController.Instance.getFolderList()) { + sendMessage(sender, f.name); + } + sendMessage(sender, "------------------------------------"); + } + + @SubCommand( + desc = "Create a custom clone folder", + usage = "", + permission = 4 + ) + public void createfolder(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String name = args[0]; + if (!CloneFolder.isValidName(name)) { + sendError(sender, String.format("Invalid folder name: %s", name)); + return; + } + if (ServerCloneController.Instance.hasFolder(name)) { + sendError(sender, String.format("Folder '%s' already exists", name)); + return; + } + CloneFolder created = ServerCloneController.Instance.createFolder(name); + if (created != null) { + sendResult(sender, String.format("Created folder \u00A7b%s", name)); + } else { + sendError(sender, String.format("Failed to create folder '%s'", name)); + } + } + + @SubCommand( + desc = "Rename a custom clone folder", + usage = " ", + permission = 4 + ) + public void renamefolder(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String oldName = args[0]; + String newName = args[1]; + if (!ServerCloneController.Instance.hasFolder(oldName)) { + sendError(sender, String.format("Unknown folder: %s", oldName)); + return; + } + if (!CloneFolder.isValidName(newName)) { + sendError(sender, String.format("Invalid folder name: %s", newName)); + return; + } + if (ServerCloneController.Instance.renameFolder(oldName, newName)) { + sendResult(sender, String.format("Renamed folder \u00A7b%s\u00A77 to \u00A7b%s", oldName, newName)); + } else { + sendError(sender, String.format("Failed to rename folder '%s'", oldName)); + } + } + + @SubCommand( + desc = "Delete an empty custom clone folder", + usage = "", + permission = 4 + ) + public void deletefolder(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String name = args[0]; + if (!ServerCloneController.Instance.hasFolder(name)) { + sendError(sender, String.format("Unknown folder: %s", name)); + return; + } + if (ServerCloneController.Instance.deleteFolder(name)) { + sendResult(sender, String.format("Deleted folder \u00A7b%s", name)); + } else { + sendError(sender, String.format("Failed to delete folder '%s' (folder must be empty)", name)); + } + } + + @SubCommand( + desc = "Move a clone between tabs/folders", + usage = " ", + permission = 4 + ) + public void move(ICommandSender sender, String[] args) { + if (ServerCloneController.Instance == null) { + sendError(sender, "Folder system not initialized"); + return; + } + String cloneName = args[0]; + + int fromTab = -1; + String fromFolder = null; + try { + fromTab = Integer.parseInt(args[1]); + if (fromTab < 1 || fromTab > 15) { + sendError(sender, "Source tab must be within 1-15"); + return; + } + } catch (NumberFormatException ex) { + fromFolder = args[1]; + if (!ServerCloneController.Instance.hasFolder(fromFolder)) { + sendError(sender, String.format("Unknown source folder: %s", fromFolder)); + return; + } + } + + int toTab = -1; + String toFolder = null; + try { + toTab = Integer.parseInt(args[2]); + if (toTab < 1 || toTab > 15) { + sendError(sender, "Destination tab must be within 1-15"); + return; + } + } catch (NumberFormatException ex) { + toFolder = args[2]; + if (!ServerCloneController.Instance.hasFolder(toFolder)) { + sendError(sender, String.format("Unknown destination folder: %s", toFolder)); + return; + } + } + + boolean success; + if (fromFolder != null && toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder); + } else if (fromFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab); + } else if (toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder); + } else { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab); + } + + if (success) { + String from = fromFolder != null ? fromFolder : String.valueOf(fromTab); + String to = toFolder != null ? toFolder : String.valueOf(toTab); + sendResult(sender, String.format("Moved \u00A7e%s\u00A77 from \u00A7b%s\u00A77 to \u00A7b%s", cloneName, from, to)); + } else { + sendError(sender, String.format("Failed to move '%s'", cloneName)); + } + } + public World getWorld(String t) { WorldServer[] ws = MinecraftServer.getServer().worldServers; for (WorldServer w : ws) { diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java index d0341f211..91356c825 100644 --- a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java +++ b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames; import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames; public class CommandKamkeel extends CommandBase { @@ -135,6 +136,9 @@ public class CommandKamkeel extends CommandBase { } else if (usage.equals("")) { List keys = getSortedEffectNames(); return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); + } else if (usage.equals("")) { + List keys = getPlayerAbilityNames(); + return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()])); } } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index e31b8f8fd..b95879c3b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -20,6 +20,7 @@ import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.controllers.AnimationController; import noppes.npcs.controllers.data.Animation; import net.minecraft.entity.player.EntityPlayer; +import noppes.npcs.controllers.data.Frame; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.entity.IPlayer; import noppes.npcs.controllers.ScriptController; @@ -28,7 +29,10 @@ import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.AbilityEvent; import noppes.npcs.scripted.event.player.PlayerAbilityEvent; +import noppes.npcs.client.gui.builder.FieldDef; + import java.util.ArrayList; +import java.util.Collections; import java.util.List; import net.minecraft.entity.Entity; @@ -56,6 +60,7 @@ public abstract class Ability implements IAbility { // Timing (ticks) protected int cooldownTicks = 0; // Added to global cooldown after ability completes protected int windUpTicks = 20; + protected boolean syncWindupWithAnimation = true; protected int dazedTicks = 80; // Only used when interrupted during WINDUP (if interruptible) // Interruption @@ -63,6 +68,8 @@ public abstract class Ability implements IAbility { // Feedback protected LockMovementType lockMovement = LockMovementType.WINDUP; + protected RotationMode rotationMode = RotationMode.FREE; + protected LockMovementType rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; protected int windUpColor = 0x80FF4400; // Telegraph color during wind up protected int activeColor = 0xC0FF0000; // Telegraph warning/active color @@ -95,6 +102,13 @@ public abstract class Ability implements IAbility { // Configurable potion effects protected List effects = new ArrayList<>(); + // Burst + protected boolean burstEnabled = false; + protected int burstAmount = 0; // number of EXTRA repetitions + protected int burstDelay = 0; // ticks between bursts + protected boolean burstReplayAnimations = true; + protected boolean burstOverlap = false; // if true, don't wait for entity death between bursts + // ═══════════════════════════════════════════════════════════════════ // EXECUTION STATE (not saved, reset each combat) // ═══════════════════════════════════════════════════════════════════ @@ -105,6 +119,17 @@ public abstract class Ability implements IAbility { protected transient long executionStartTime; protected transient TelegraphInstance telegraphInstance; + // Burst execution state + protected transient int burstIndex = 0; + protected transient List burstEntities = new ArrayList<>(); + + // ═══════════════════════════════════════════════════════════════════ + // PREVIEW STATE (client-side only, not saved) + // ═══════════════════════════════════════════════════════════════════ + + protected transient boolean previewMode = false; + protected transient PreviewEntityHandler previewEntityHandler; + // ═══════════════════════════════════════════════════════════════════ // ABSTRACT METHODS // ═══════════════════════════════════════════════════════════════════ @@ -133,6 +158,60 @@ public abstract class Ability implements IAbility { // OPTIONAL OVERRIDES // ═══════════════════════════════════════════════════════════════════ + /** + * Returns true if this ability type deals damage. + * Override in non-damaging subclasses to return false. + * Used by external mods to determine whether to show + * damage-related configuration (e.g., DBC stats tab). + */ + public boolean hasDamage() { + return true; + } + + /** + * Override to provide variant templates for this ability type. + * When a user creates this ability type, they will be shown a selection dialog + * with the returned variants. If empty or single-entry, the dialog is skipped. + */ + public List getVariants() { + return Collections.emptyList(); + } + + /** + * Whether this ability type supports the burst system. + * Override to return false for abilities that shouldn't repeat (Guard, Heal, Sweeper, etc.). + */ + public boolean allowBurst() { + return true; + } + + /** + * Whether this ability supports overlap mode for burst (entities from previous bursts keep flying). + * Override to return true for entity-spawning projectile abilities (Orb, Beam, Disc, LaserShot). + */ + public boolean allowOverlap() { + return false; + } + + /** + * Whether this ability is ready for auto-completion during burst overlap mode. + * Override to delay auto-completion until all staggered projectiles have been fired. + * @param activeTick the current tick within the ACTIVE phase + */ + public boolean isReadyForBurstCompletion(int activeTick) { + return true; + } + + /** + * Called when burst re-fires without replay animations (burstReplayAnimations=false). + * Entity-spawning abilities should override to spawn and fire entities in one step, + * since onWindUpTick was not called (windup was skipped). + * Default: does nothing (ability goes directly to onExecute with existing state). + */ + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + // Override in entity-spawning abilities (Orb, Beam, Disc, LaserShot) + } + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { } @@ -142,6 +221,9 @@ public abstract class Ability implements IAbility { public void onComplete(EntityLivingBase caster, EntityLivingBase target) { } + public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) { + } + /** * Apply damage to an entity with ability hit event support. * Fires the abilityHit script event, allowing scripts to modify or cancel the damage. @@ -239,12 +321,22 @@ public abstract class Ability implements IAbility { // Apply damage if (damage > 0) { - if (caster instanceof EntityNPCInterface) { - hitEntity.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), damage); - } else if (caster instanceof EntityPlayer) { - hitEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) caster), damage); - } else { - hitEntity.attackEntityFrom(DamageSource.causeMobDamage(caster), damage); + // Check for external damage handler first (e.g., DBC Addon) + IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler(); + boolean handled = false; + if (handler != null) { + handled = handler.handleDamage(this, caster, hitEntity, damage, knockback, knockbackUp, + knockbackDirX, knockbackDirZ); + } + if (!handled) { + // Default damage path + if (caster instanceof EntityNPCInterface) { + hitEntity.attackEntityFrom(new NpcDamageSource("mob", (EntityNPCInterface) caster), damage); + } else if (caster instanceof EntityPlayer) { + hitEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) caster), damage); + } else { + hitEntity.attackEntityFrom(DamageSource.causeMobDamage(caster), damage); + } } } @@ -300,6 +392,18 @@ public abstract class Ability implements IAbility { return 45.0f; } + /** + * Returns true if the caster is a player (not an NPC). + * Use this instead of checking {@code target != null} to make NPC/Player + * code paths explicit and readable. + *

+ * NPCs always have an aggro target passed to ability methods. + * Players never do — they use look direction for aiming instead. + */ + protected final boolean isPlayerCaster(EntityLivingBase caster) { + return caster instanceof EntityPlayer; + } + /** * Returns true if this ability controls NPC movement during ACTIVE phase. * When true, AI pathfinding will be blocked during ability execution. @@ -335,19 +439,178 @@ public abstract class Ability implements IAbility { } /** - * Returns true if this ability type has custom settings that need a Type-specific tab. - * Override to return true if the ability has settings beyond the base Ability fields. + * Add field definitions for this ability's GUI. + * Override in subclasses to add type-specific fields. The list already contains + * the base fields (General, Target, Effects tabs), so subclasses can also + * modify, insert into, or remove base fields using {@link FieldDef#insertBefore}, + * {@link FieldDef#insertAfter}, or direct list manipulation. + *

+ * Fields added here without an explicit {@code .tab()} will default to the "Type" tab. + * + * @param defs The mutable list of field definitions to add to or modify */ - public boolean hasTypeSettings() { - return false; + @SideOnly(Side.CLIENT) + public void getAbilityDefinitions(List defs) { } /** - * Get the number of rows needed for type-specific settings in the GUI. - * Each row is approximately 24 pixels. Used for GUI layout. + * Builds and returns all field definitions for this ability's GUI. + * Base fields (General, Target, Effects) are added first, then + * {@link #getAbilityDefinitions(List)} is called so subclasses can add + * type-specific fields and modify any existing fields. */ - public int getTypeSettingsRowCount() { - return 0; + @SideOnly(Side.CLIENT) + public final List getAllDefinitions() { + List defs = new ArrayList<>(); + + // ── General tab ────────────────────────────────────────────── + defs.add(FieldDef.stringField("gui.name", this::getName, this::setName) + .tab("General")); + defs.add(FieldDef.row( + FieldDef.intField("ability.weight", this::getWeight, this::setWeight).range(1, 1000), + FieldDef.boolField("gui.enabled", this::isEnabled, this::setEnabled) + ).tab("General")); + defs.add(FieldDef.section("ability.section.timing").tab("General")); + defs.add(FieldDef.intField("ability.windUpTicks", this::getRawWindUpTicks, this::setWindUpTicks) + .tab("General").range(0, 1000) + .visibleWhen(() -> !hasWindUpAnimation())); + defs.add(FieldDef.row( + FieldDef.intField("ability.windUpTicks", this::getRawWindUpTicks, this::setWindUpTicks).range(0, 1000), + FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation) + .hover("ability.hover.sync") + ).tab("General").visibleWhen(() -> hasWindUpAnimation() && !isSyncWindupWithAnimation())); + defs.add(FieldDef.row( + FieldDef.labelField("ability.windUpTicks", () -> getWindUpTicks() + "t"), + FieldDef.boolField("ability.syncWindup", this::isSyncWindupWithAnimation, this::setSyncWindupWithAnimation) + .hover("ability.hover.sync") + ).tab("General").visibleWhen(() -> hasWindUpAnimation() && isSyncWindupWithAnimation())); + defs.add(FieldDef.intField("ability.cooldownTicks", this::getCooldownTicks, this::setCooldownTicks) + .tab("General").range(0, 10000)); + defs.add(FieldDef.section("ability.section.movement").tab("General")); + defs.add(FieldDef.stringEnumField("ability.lockMovement", LockMovementType.getDisplayKeys(), + () -> this.getLockMovement().getDisplayKey(), + v -> { + for (LockMovementType t : LockMovementType.values()) { + if (t.getDisplayKey().equals(v)) { this.setLockMovement(t); break; } + } + }) + .hover("ability.hover.lockMovement") + .tab("General")); + defs.add(FieldDef.row( + FieldDef.stringEnumField("ability.rotationMode", RotationMode.getDisplayKeys(), + () -> this.getRotationMode().getDisplayKey(), + v -> { + for (RotationMode m : RotationMode.values()) { + if (m.getDisplayKey().equals(v)) { this.setRotationMode(m); break; } + } + }) + .hover("ability.hover.rotationMode"), + FieldDef.stringEnumField("ability.rotationPhase", getRotationPhaseKeys(), + () -> this.getRotationPhase().getDisplayKey(), + v -> { + for (LockMovementType t : LockMovementType.values()) { + if (t.getDisplayKey().equals(v)) { this.setRotationPhase(t); break; } + } + }) + .hover("ability.hover.rotationPhase") + .visibleWhen(() -> this.rotationMode != RotationMode.FREE) + ).tab("General")); + defs.add(FieldDef.row( + FieldDef.boolField("ability.interruptible", this::isInterruptible, this::setInterruptible) + .hover("ability.hover.interruptible"), + FieldDef.intField("ability.dazedTicks", this::getDazedTicks, this::setDazedTicks) + .range(0, 1000).visibleWhen(this::isInterruptible) + ).tab("General")); + + // ── Burst section ──────────────────────────────────────────── + if (allowBurst()) { + defs.add(FieldDef.section("ability.section.burst").tab("General")); + defs.add(FieldDef.boolField("ability.burstEnabled", this::isBurstEnabled, this::setBurstEnabled) + .tab("General")); + defs.add(FieldDef.row( + FieldDef.intField("ability.burstAmount", this::getBurstAmount, this::setBurstAmount).range(1, 100), + FieldDef.intField("ability.burstDelay", this::getBurstDelay, this::setBurstDelay).range(0, 1000) + ).tab("General").visibleWhen(this::isBurstEnabled)); + defs.add(FieldDef.boolField("ability.burstReplayAnimations", this::isBurstReplayAnimations, this::setBurstReplayAnimations) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstReplay")); + if (allowOverlap()) { + defs.add(FieldDef.boolField("ability.burstOverlap", this::isBurstOverlap, this::setBurstOverlap) + .tab("General").visibleWhen(this::isBurstEnabled) + .hover("ability.hover.burstOverlap")); + } + } + + // ── Target tab ─────────────────────────────────────────────── + defs.add(FieldDef.row( + FieldDef.intField("ability.minRange", () -> (int) getMinRange(), v -> setMinRange(v)).range(0, 100), + FieldDef.intField("ability.maxRange", () -> (int) getMaxRange(), v -> setMaxRange(v)).range(1, 100) + ).tab("Target")); + if (!isTargetingModeLocked()) { + TargetingMode[] allowed = getAllowedTargetingModes(); + if (allowed != null && allowed.length > 0) { + String[] allowedKeys = new String[allowed.length]; + for (int i = 0; i < allowed.length; i++) { + allowedKeys[i] = allowed[i].name(); + } + defs.add(FieldDef.stringEnumField("ability.targetingMode", allowedKeys, + () -> this.getTargetingMode().name(), + v -> { + try { this.setTargetingMode(TargetingMode.valueOf(v)); } + catch (Exception ignored) {} + }) + .tab("Target").hover("ability.hover.targeting")); + } else { + defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class, + this::getTargetingMode, this::setTargetingMode) + .tab("Target").hover("ability.hover.targeting")); + } + } + + // ── Effects tab ────────────────────────────────────────────── + defs.add(FieldDef.section("ability.section.sounds").tab("Effects")); + defs.add(FieldDef.soundSubGui("ability.windUpSound", this::getWindUpSound, this::setWindUpSound) + .tab("Effects")); + defs.add(FieldDef.soundSubGui("ability.activeSound", this::getActiveSound, this::setActiveSound) + .tab("Effects")); + defs.add(FieldDef.section("ability.section.animations").tab("Effects")); + defs.add(FieldDef.animSubGui("ability.windUpAnimation", + this::getWindUpAnimationId, this::setWindUpAnimationId, + this::getWindUpAnimationName, this::setWindUpAnimationName) + .tab("Effects")); + defs.add(FieldDef.animSubGui("ability.activeAnimation", + this::getActiveAnimationId, this::setActiveAnimationId, + this::getActiveAnimationName, this::setActiveAnimationName) + .tab("Effects")); + + TelegraphType tType = getTelegraphType(); + if (tType != null && tType != TelegraphType.NONE) { + defs.add(FieldDef.section("ability.section.telegraph").tab("Effects") + .hover("telegraph." + tType.name().toLowerCase())); + defs.add(FieldDef.boolField("ability.showTelegraph", this::isShowTelegraph, this::setShowTelegraph) + .tab("Effects").hover("ability.hover.showTelegraph")); + defs.add(FieldDef.colorSubGui("ability.windUpColor", this::getWindUpColor, this::setWindUpColor) + .tab("Effects").visibleWhen(this::isShowTelegraph)); + defs.add(FieldDef.colorSubGui("ability.activeColor", this::getActiveColor, this::setActiveColor) + .tab("Effects").visibleWhen(this::isShowTelegraph)); + } + + // ── Type-specific fields ───────────────────────────────────── + int baseSize = defs.size(); + getAbilityDefinitions(defs); + // Default tab for ability-added fields that don't specify one + for (int i = baseSize; i < defs.size(); i++) { + if (defs.get(i).getTab() == null) { + defs.get(i).tab("Type"); + } + } + + // External field providers (e.g., DBC Addon injecting a "DBC" tab) + for (IAbilityFieldProvider provider : AbilityController.Instance.getFieldProviders()) { + provider.addFieldDefinitions(this, defs); + } + + return defs; } /** @@ -438,8 +701,12 @@ public abstract class Ability implements IAbility { instance.setEntityIdToFollow(caster.getEntityId()); // For LINE/CONE telegraphs: track target direction during windup + // Only track if rotation is NOT locked during windup (NPC can still turn) if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) { - instance.setTargetEntityId(target.getEntityId()); + if (!isRotationLockedDuringWindup()) { + instance.setTargetEntityId(target.getEntityId()); + } + // If rotation is locked, yaw stays fixed at creation time } } else if (target != null) { // AOE_TARGET abilities: telegraph follows target during windup @@ -535,13 +802,21 @@ public abstract class Ability implements IAbility { // ═══════════════════════════════════════════════════════════════════ /** - * Start executing this ability + * Start executing this ability. + * If windUpTicks is 0, skips WINDUP and goes directly to ACTIVE. */ public void start(EntityLivingBase target) { - this.phase = AbilityPhase.WINDUP; this.currentTick = 0; this.currentTarget = target; this.executionStartTime = System.currentTimeMillis(); + this.burstIndex = 0; + this.burstEntities.clear(); + + if (windUpTicks <= 0) { + this.phase = AbilityPhase.ACTIVE; + } else { + this.phase = AbilityPhase.WINDUP; + } } /** @@ -578,6 +853,19 @@ public abstract class Ability implements IAbility { return true; } break; + + case BURST_DELAY: + // Waiting between burst repetitions - free movement/rotation + if (currentTick >= burstDelay) { + if (burstReplayAnimations && getWindUpTicks() > 0) { + phase = AbilityPhase.WINDUP; + } else { + phase = AbilityPhase.ACTIVE; + } + currentTick = 0; + return true; + } + break; } return false; } @@ -591,6 +879,19 @@ public abstract class Ability implements IAbility { */ public boolean signalCompletion() { if (phase == AbilityPhase.ACTIVE) { + // Check if more burst iterations remain + if (burstEnabled && burstAmount > 0 && burstIndex < burstAmount) { + if (!burstOverlap) { + cleanup(); + } + burstIndex++; + phase = AbilityPhase.BURST_DELAY; + currentTick = 0; + return true; + } + + // Final completion - let burst entities die naturally (don't force-kill) + burstEntities.clear(); cleanup(); phase = AbilityPhase.IDLE; currentTick = 0; @@ -604,9 +905,10 @@ public abstract class Ability implements IAbility { * Called when NPC takes direct damage during WINDUP. */ public void interrupt() { + cleanupBurstEntities(); cleanup(); - if (interruptible && phase == AbilityPhase.WINDUP) { - // Interrupted during windup - go to dazed state + if (interruptible && (phase == AbilityPhase.WINDUP || phase == AbilityPhase.BURST_DELAY)) { + // Interrupted during windup or burst delay - go to dazed state phase = AbilityPhase.DAZED; currentTick = 0; } else { @@ -614,6 +916,7 @@ public abstract class Ability implements IAbility { phase = AbilityPhase.IDLE; currentTick = 0; } + burstIndex = 0; currentTarget = null; telegraphInstance = null; } @@ -634,7 +937,7 @@ public abstract class Ability implements IAbility { * @return true if the ability should be interrupted */ public boolean canInterrupt(DamageSource source) { - if (!interruptible || phase != AbilityPhase.WINDUP) { + if (!interruptible || (phase != AbilityPhase.WINDUP && phase != AbilityPhase.BURST_DELAY)) { return false; } @@ -661,11 +964,15 @@ public abstract class Ability implements IAbility { * Reset all execution state (called on combat end, NPC death, target lost, etc.) */ public void reset() { + cleanupBurstEntities(); cleanup(); phase = AbilityPhase.IDLE; currentTick = 0; + burstIndex = 0; currentTarget = null; telegraphInstance = null; + previewMode = false; + previewEntityHandler = null; } /** @@ -677,91 +984,73 @@ public abstract class Ability implements IAbility { // Override in subclasses to clean up spawned entities, etc. } + /** + * Kill all entities tracked during burst overlap and clear the list. + */ + protected void cleanupBurstEntities() { + for (Entity e : burstEntities) { + if (e != null && !e.isDead) { + killAbilityEntity(e); + } + } + burstEntities.clear(); + } + // ═══════════════════════════════════════════════════════════════════ - // CLIENT-SIDE PREVIEW METHODS + // PREVIEW MODE SUPPORT // ═══════════════════════════════════════════════════════════════════ /** - * Get total active phase duration for preview (in ticks). - * Override in subclasses to provide accurate preview duration. - * - * @return Duration of active phase in ticks (default: 40 = 2 seconds) + * Whether this ability is running in preview mode (GUI preview). + * When true, abilities should skip damage, effects, sounds, and particles + * but still run their core logic (entity spawning, movement, timing). */ - public int getPreviewActiveDuration() { - return 40; + public boolean isPreview() { + return previewMode; + } + + public void setPreviewMode(boolean preview) { + this.previewMode = preview; + } + + public void setPreviewEntityHandler(PreviewEntityHandler handler) { + this.previewEntityHandler = handler; } /** - * Called during preview windup tick (client-side only). - * Override for visual updates during windup preview. - * Do NOT apply damage or world effects here. - * - * @param npc The preview NPC - * @param tick Current tick within windup phase + * Spawn an entity during ability execution. + * In preview mode, routes to PreviewEntityHandler instead of world.spawnEntityInWorld(). */ - @SideOnly(Side.CLIENT) - public void onPreviewWindUpTick(EntityNPCInterface npc, int tick) { - // Default: no-op. Override in subclasses for visual effects. + protected void spawnAbilityEntity(World world, Entity entity) { + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntitySpawned(entity); + } else { + world.spawnEntityInWorld(entity); + } + if (burstEnabled && burstOverlap) { + burstEntities.add(entity); + } } /** - * Called during preview active tick (client-side only). - * Override for visual updates during active preview. - * Do NOT apply damage or world effects here. - * - * @param npc The preview NPC - * @param tick Current tick within active phase + * Kill an entity spawned by this ability. + * In preview mode, notifies PreviewEntityHandler of removal. */ - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - // Default: no-op. Override in subclasses for visual effects. + protected void killAbilityEntity(Entity entity) { + if (entity == null) return; + entity.setDead(); + if (previewMode && previewEntityHandler != null) { + previewEntityHandler.onEntityRemoved(entity); + } } /** - * Create a preview entity for GUI display (client-side only). - * The entity should be in preview mode and not apply damage. - * Override in abilities that spawn entities (Beam, Orb, Disc, etc.) - * - * @param npc The preview NPC - * @return Preview entity, or null if ability doesn't spawn entities + * Maximum duration (in ticks) for preview before auto-stopping. + * Override in movement abilities that have variable duration. + * Default: 200 ticks (10 seconds). */ - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - return null; // Override in entity-spawning abilities - } - - /** - * Whether to spawn preview entity during WINDUP phase (true) or ACTIVE phase (false). - * Most abilities (Orb, Beam, Disc) spawn during windup for charging effect. - * Laser spawns at active phase since it has no charging state. - */ - public boolean spawnPreviewDuringWindup() { - return true; // Default: spawn during windup for charging - } - - // ── Preview target (set by executor for abilities that need targeting) ── - - protected transient EntityLivingBase previewTarget; - - /** - * Set the fake target entity for preview mode. - * Called by AbilityPreviewExecutor before starting preview. - */ - public void setPreviewTarget(EntityLivingBase target) { - this.previewTarget = target; - } - - public EntityLivingBase getPreviewTarget() { - return previewTarget; - } - - /** - * Called once when transitioning from WINDUP to ACTIVE in preview mode. - * Override in movement-based abilities to initiate movement. - */ - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - // Default: no-op. Override in movement abilities. + public int getMaxPreviewDuration() { + return 200; } // ═══════════════════════════════════════════════════════════════════ @@ -803,9 +1092,12 @@ public abstract class Ability implements IAbility { nbt.setFloat("maxRange", maxRange); nbt.setInteger("cooldown", cooldownTicks); nbt.setInteger("windUp", windUpTicks); + nbt.setBoolean("syncWindup", syncWindupWithAnimation); nbt.setInteger("recovery", dazedTicks); nbt.setBoolean("interruptible", interruptible); nbt.setInteger("lockMovement", lockMovement.ordinal()); + nbt.setInteger("rotationMode", rotationMode.ordinal()); + nbt.setInteger("rotationPhase", rotationPhase.ordinal()); nbt.setInteger("windUpColor", windUpColor); nbt.setInteger("activeColor", activeColor); nbt.setString("windUpSound", windUpSound); @@ -821,6 +1113,13 @@ public abstract class Ability implements IAbility { nbt.setInteger("allowedBy", allowedBy.ordinal()); nbt.setBoolean("ignoreCooldown", ignoreCooldown); + // Burst + nbt.setBoolean("burstEnabled", burstEnabled); + nbt.setInteger("burstAmount", burstAmount); + nbt.setInteger("burstDelay", burstDelay); + nbt.setBoolean("burstReplayAnimations", burstReplayAnimations); + nbt.setBoolean("burstOverlap", burstOverlap); + // Conditions NBTTagList condList = new NBTTagList(); for (Condition c : conditions) condList.appendTag(c.writeNBT()); @@ -852,9 +1151,34 @@ public abstract class Ability implements IAbility { maxRange = nbt.getFloat("maxRange"); cooldownTicks = nbt.getInteger("cooldown"); windUpTicks = nbt.getInteger("windUp"); + syncWindupWithAnimation = !nbt.hasKey("syncWindup") || nbt.getBoolean("syncWindup"); dazedTicks = nbt.getInteger("recovery"); interruptible = nbt.getBoolean("interruptible"); lockMovement = LockMovementType.fromOrdinal(nbt.getInteger("lockMovement")); + if (nbt.hasKey("rotationMode")) { + // Current format + rotationMode = RotationMode.fromOrdinal(nbt.getInteger("rotationMode")); + rotationPhase = LockMovementType.fromOrdinal(nbt.getInteger("rotationPhase")); + } else if (nbt.hasKey("lockType")) { + // Legacy format migration: lockType was LockType enum (0=MOVEMENT, 1=ROTATION, 2=BOTH) + int oldLockType = nbt.getInteger("lockType"); + if (oldLockType == 0) { + // MOVEMENT only: movement locked, rotation was free + rotationMode = RotationMode.FREE; + } else if (oldLockType == 1) { + // ROTATION only: rotation locked same timing as old lockMovement, movement was free + rotationMode = RotationMode.LOCKED; + rotationPhase = lockMovement; + lockMovement = LockMovementType.NO; + } else { + // BOTH: both locked same timing + rotationMode = RotationMode.LOCKED; + rotationPhase = lockMovement; + } + } else { + rotationMode = RotationMode.FREE; + rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; + } windUpColor = nbt.getInteger("windUpColor"); activeColor = nbt.getInteger("activeColor"); windUpSound = nbt.getString("windUpSound"); @@ -876,6 +1200,13 @@ public abstract class Ability implements IAbility { allowedBy = nbt.hasKey("allowedBy") ? UserType.fromOrdinal(nbt.getInteger("allowedBy")) : UserType.BOTH; ignoreCooldown = nbt.hasKey("ignoreCooldown") && nbt.getBoolean("ignoreCooldown"); + // Burst + burstEnabled = nbt.hasKey("burstEnabled") && nbt.getBoolean("burstEnabled"); + burstAmount = nbt.hasKey("burstAmount") ? nbt.getInteger("burstAmount") : 0; + burstDelay = nbt.hasKey("burstDelay") ? nbt.getInteger("burstDelay") : 0; + burstReplayAnimations = !nbt.hasKey("burstReplayAnimations") || nbt.getBoolean("burstReplayAnimations"); + burstOverlap = nbt.hasKey("burstOverlap") && nbt.getBoolean("burstOverlap"); + // Conditions conditions.clear(); NBTTagList condList = nbt.getTagList("conditions", 10); @@ -972,6 +1303,10 @@ public abstract class Ability implements IAbility { } public int getWindUpTicks() { + return calculateWindupFromAnimation(); + } + + public int getRawWindUpTicks() { return windUpTicks; } @@ -979,6 +1314,18 @@ public abstract class Ability implements IAbility { this.windUpTicks = Math.max(0, windUpTicks); } + public boolean isSyncWindupWithAnimation() { + return syncWindupWithAnimation; + } + + public boolean hasWindUpAnimation() { + return (windUpAnimationName != null && !windUpAnimationName.isEmpty()) || windUpAnimationId >= 0; + } + + public void setSyncWindupWithAnimation(boolean syncWindupWithAnimation) { + this.syncWindupWithAnimation = syncWindupWithAnimation; + } + public int getDazedTicks() { return dazedTicks; } @@ -1003,6 +1350,22 @@ public abstract class Ability implements IAbility { this.lockMovement = lockMovement; } + public RotationMode getRotationMode() { + return rotationMode; + } + + public void setRotationMode(RotationMode rotationMode) { + this.rotationMode = rotationMode; + } + + public LockMovementType getRotationPhase() { + return rotationPhase; + } + + public void setRotationPhase(LockMovementType rotationPhase) { + this.rotationPhase = rotationPhase; + } + /** * API method: Get lock movement type as integer. * @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE @@ -1022,7 +1385,43 @@ public abstract class Ability implements IAbility { } /** - * Check if movement should be locked during WINDUP phase. + * API method: Get rotation mode as integer. + * @return 0=FREE, 1=LOCKED, 2=TRACK + */ + @Override + public int getRotationModeType() { + return rotationMode.ordinal(); + } + + /** + * API method: Set rotation mode from integer. + * @param type 0=FREE, 1=LOCKED, 2=TRACK + */ + @Override + public void setRotationModeType(int type) { + this.rotationMode = RotationMode.fromOrdinal(type); + } + + /** + * API method: Get rotation phase as integer. + * @return 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public int getRotationPhaseType() { + return rotationPhase.ordinal(); + } + + /** + * API method: Set rotation phase from integer. + * @param type 0=NO, 1=WINDUP, 2=ACTIVE, 3=WINDUP_AND_ACTIVE + */ + @Override + public void setRotationPhaseType(int type) { + this.rotationPhase = LockMovementType.fromOrdinal(type); + } + + /** + * Check if movement (pathfinding/motion) should be locked during WINDUP phase. */ @Override public boolean isMovementLockedDuringWindup() { @@ -1030,22 +1429,73 @@ public abstract class Ability implements IAbility { } /** - * Check if movement should be locked during ACTIVE phase. + * Check if movement (pathfinding/motion) should be locked during ACTIVE phase. */ @Override public boolean isMovementLockedDuringActive() { return lockMovement.locksActive(); } + /** + * Check if rotation (yaw/pitch) should be locked during WINDUP phase. + */ + @Override + public boolean isRotationLockedDuringWindup() { + return rotationMode == RotationMode.LOCKED && rotationPhase.locksWindup(); + } + + /** + * Check if rotation (yaw/pitch) should be locked during ACTIVE phase. + */ + @Override + public boolean isRotationLockedDuringActive() { + return rotationMode == RotationMode.LOCKED && rotationPhase.locksActive(); + } + /** * Check if movement should be locked during the current phase. */ public boolean isMovementLockedForCurrentPhase() { switch (phase) { case WINDUP: - return lockMovement.locksWindup(); + return isMovementLockedDuringWindup(); case ACTIVE: - return lockMovement.locksActive(); + return isMovementLockedDuringActive(); + case BURST_DELAY: + return false; // Free movement during burst delay + default: + return false; + } + } + + /** + * Check if rotation should be locked during the current phase. + */ + public boolean isRotationLockedForCurrentPhase() { + switch (phase) { + case WINDUP: + return isRotationLockedDuringWindup(); + case ACTIVE: + return isRotationLockedDuringActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay + default: + return false; + } + } + + /** + * Check if hit scan (force face target) is active during the current phase. + */ + public boolean isHitScanForCurrentPhase() { + if (rotationMode != RotationMode.TRACK) return false; + switch (phase) { + case WINDUP: + return rotationPhase.locksWindup(); + case ACTIVE: + return rotationPhase.locksActive(); + case BURST_DELAY: + return false; // Free rotation during burst delay default: return false; } @@ -1088,7 +1538,7 @@ public abstract class Ability implements IAbility { // Built-in animation by name takes priority if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { - return (Animation) AnimationController.Instance.get(windUpAnimationName); + return (Animation) AnimationController.Instance.get(windUpAnimationName, true); } // Fall back to user animation by ID if (windUpAnimationId >= 0) { @@ -1118,7 +1568,7 @@ public abstract class Ability implements IAbility { // Built-in animation by name takes priority if (activeAnimationName != null && !activeAnimationName.isEmpty()) { - return (Animation) AnimationController.Instance.get(activeAnimationName); + return (Animation) AnimationController.Instance.get(activeAnimationName, true); } // Fall back to user animation by ID if (activeAnimationId >= 0) { @@ -1234,6 +1684,100 @@ public abstract class Ability implements IAbility { effects.clear(); } + // Burst getters/setters + + public boolean isBurstEnabled() { + return burstEnabled; + } + + public void setBurstEnabled(boolean burstEnabled) { + this.burstEnabled = burstEnabled; + } + + public int getBurstAmount() { + return burstAmount; + } + + public void setBurstAmount(int burstAmount) { + this.burstAmount = Math.max(0, burstAmount); + } + + public int getBurstDelay() { + return burstDelay; + } + + public void setBurstDelay(int burstDelay) { + this.burstDelay = Math.max(0, burstDelay); + } + + public boolean isBurstReplayAnimations() { + return burstReplayAnimations; + } + + public void setBurstReplayAnimations(boolean burstReplayAnimations) { + this.burstReplayAnimations = burstReplayAnimations; + } + + public boolean isBurstOverlap() { + return burstOverlap; + } + + public void setBurstOverlap(boolean burstOverlap) { + this.burstOverlap = burstOverlap; + } + + public int getBurstIndex() { + return burstIndex; + } + + /** + * Get display keys for rotation phase dropdown (excludes "None" since mode=FREE handles that). + */ + private static String[] getRotationPhaseKeys() { + return new String[]{ + "ability.lockMove.windup", + "ability.lockMove.active", + "ability.lockMove.both" + }; + } + + // ═══════════════════════════════════════════════════════════════════ + // SHIT FROM THE ASS + // ═══════════════════════════════════════════════════════════════════ + + private int calculateWindupFromAnimation() { + if (!syncWindupWithAnimation) { + return windUpTicks; + } + + if (AnimationController.Instance == null) { + return this.windUpTicks; + } + + Animation animation = null; + // Check for built-in animation (by name) first + if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { + animation = (Animation) AnimationController.Instance.get(windUpAnimationName, true); + } + // Fall back to user animation (by ID) + else if (windUpAnimationId >= 0) { + animation = (Animation) AnimationController.Instance.get(windUpAnimationId); + } + + if (animation == null || animation.frames.isEmpty()) { + return this.windUpTicks; + } + + // Calculate total duration by summing all frame durations + int totalDuration = 0; + for (Frame frame : animation.frames) { + totalDuration += frame.getDuration(); + } + + // Return total duration + return totalDuration; + } + // ═══════════════════════════════════════════════════════════════════ // IAbility API METHODS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java index 62d226bf7..294f9a765 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityController.java @@ -1,23 +1,6 @@ package kamkeel.npcs.controllers.data.ability; -import kamkeel.npcs.controllers.data.ability.type.AbilitySweeper; -import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; -import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; -import kamkeel.npcs.controllers.data.ability.type.AbilityDash; -import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; -import kamkeel.npcs.controllers.data.ability.type.AbilityHazard; -import kamkeel.npcs.controllers.data.ability.type.AbilityHeal; -import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit; -import kamkeel.npcs.controllers.data.ability.type.AbilityOrb; -import kamkeel.npcs.controllers.data.ability.type.AbilityDisc; -import kamkeel.npcs.controllers.data.ability.type.AbilityLaserShot; -import kamkeel.npcs.controllers.data.ability.type.AbilityEnergyBeam; -import kamkeel.npcs.controllers.data.ability.type.AbilityProjectile; -import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave; -import kamkeel.npcs.controllers.data.ability.type.AbilitySlam; -import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport; -import kamkeel.npcs.controllers.data.ability.type.AbilityTrap; -import kamkeel.npcs.controllers.data.ability.type.AbilityVortex; +import kamkeel.npcs.controllers.data.ability.type.*; import kamkeel.npcs.controllers.SyncController; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcs; @@ -56,6 +39,15 @@ public class AbilityController implements IAbilityHandler { * Used by AbilitySlot for cache invalidation. */ private int version = 0; + /** External damage handler (e.g., DBC Addon). */ + private IAbilityDamageHandler damageHandler = null; + + /** External field providers for ability GUI (e.g., DBC Addon). Client-side only. */ + private final List fieldProviders = new ArrayList<>(); + + /** External variant definitions registered by addons, keyed by typeId. */ + private final Map> externalVariants = new LinkedHashMap<>(); + public AbilityController() { registerBuiltinTypes(); } @@ -191,30 +183,93 @@ public class AbilityController implements IAbilityHandler { // ═══════════════════════════════════════════════════════════════════════════ /** - * Resolve an ability by key. Checks built-in abilities first (by name), - * then custom abilities (by UUID). Returns a copy safe to modify. + * Resolve an ability by key. Checks built-in abilities first (by name or registry key), + * then custom abilities (by UUID or name). Returns a copy safe to modify for + * custom abilities, or the singleton instance for built-in abilities. * - * @param key The ability name (built-in) or UUID (custom) - * @return A copy of the resolved ability, or null if not found + * @param key The ability name, registry key (built-in) or UUID (custom) + * @return The resolved ability, or null if not found */ public Ability resolveAbility(String key) { if (key == null || key.isEmpty()) return null; - // Check built-in abilities first + // Check built-in abilities first (exact match by name) Ability builtIn = abilities.get(key); if (builtIn != null) { - return fromNBT(builtIn.writeNBT()); + return builtIn; } - // Check custom abilities + // Check built-in abilities by name (case-insensitive) + for (Map.Entry entry : abilities.entrySet()) { + if (entry.getKey().equalsIgnoreCase(key)) { + return entry.getValue(); + } + } + + // Check built-in abilities by registry key / ID + for (Ability ability : abilities.values()) { + if (ability.getId() != null && ability.getId().equalsIgnoreCase(key)) { + return ability; + } + } + + // Check custom abilities (exact UUID match) Ability custom = customAbilities.get(key); if (custom != null) { return fromNBT(custom.writeNBT()); } + // Check custom abilities by name (case-insensitive) + for (Ability ability : customAbilities.values()) { + if (ability.getName() != null && ability.getName().equalsIgnoreCase(key)) { + return fromNBT(ability.writeNBT()); + } + } + return null; } + /** + * Get all keys that can be used to look up abilities (for tab completion). + * Returns registry keys for built-in abilities (no spaces) and UUIDs for custom. + */ + public Set getAbilityKeys() { + Set keys = new LinkedHashSet<>(); + // Built-in abilities - use the ID (registry key for BuiltInAbility) + for (Ability ability : abilities.values()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + // Custom abilities - use UUID + keys.addAll(customAbilities.keySet()); + return keys; + } + + /** + * Get keys for player-usable abilities only (for tab completion). + */ + public Set getPlayerAbilityKeys() { + Set keys = new LinkedHashSet<>(); + // Built-in abilities - use the ID (registry key for BuiltInAbility) + for (Ability ability : abilities.values()) { + if (ability.getAllowedBy().allowsPlayer()) { + String id = ability.getId(); + if (id != null && !id.isEmpty()) { + keys.add(id); + } + } + } + // Custom abilities - use UUID (if player-usable) + for (Map.Entry entry : customAbilities.entrySet()) { + if (entry.getValue().getAllowedBy().allowsPlayer()) { + keys.add(entry.getKey()); + } + } + return keys; + } + /** * Check if an ability key exists (either built-in or custom). */ @@ -382,7 +437,7 @@ public class AbilityController implements IAbilityHandler { registerType("cnpc:orb", AbilityOrb::new); registerType("cnpc:disc", AbilityDisc::new); registerType("cnpc:laser_shot", AbilityLaserShot::new); - registerType("cnpc:beam", AbilityEnergyBeam::new); + registerType("cnpc:beam", AbilityBeam::new); // Movement abilities registerType("cnpc:charge", AbilityCharge::new); @@ -399,4 +454,76 @@ public class AbilityController implements IAbilityHandler { registerType("cnpc:hazard", AbilityHazard::new); registerType("cnpc:trap", AbilityTrap::new); } + + // ═══════════════════════════════════════════════════════════════════════════ + // EXTERNAL DAMAGE HANDLER + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Register an external damage handler for abilities. + * When set, the handler is called before default damage application. + * If the handler returns true, default damage is skipped. + */ + public void registerDamageHandler(IAbilityDamageHandler handler) { + this.damageHandler = handler; + } + + /** Get the registered damage handler, or null if none. */ + public IAbilityDamageHandler getDamageHandler() { + return damageHandler; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // EXTERNAL FIELD PROVIDERS + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Register an external field provider for ability GUIs. + * Providers are called during getAllDefinitions() to inject custom tabs/fields. + */ + public void registerFieldProvider(IAbilityFieldProvider provider) { + fieldProviders.add(provider); + } + + /** Get all registered field providers. */ + public List getFieldProviders() { + return fieldProviders; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // EXTERNAL VARIANT REGISTRY + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Register an external variant for an ability type. + * External mods can call this to add variant presets that appear + * alongside built-in variants in the variant selection SubGui. + * + * @param typeId The ability typeId (e.g., "ability.cnpc.beam") + * @param variant The variant to register + */ + public void registerVariant(String typeId, AbilityVariant variant) { + externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant); + } + + /** + * Get all variants for a given ability type (built-in + external). + * Returns the combined list of variants from the ability's getVariants() + * and any externally registered variants. + * + * @param typeId The ability typeId + * @return Combined list of variants, empty if none + */ + public List getVariantsForType(String typeId) { + List result = new ArrayList<>(); + Ability temp = create(typeId); + if (temp != null) { + result.addAll(temp.getVariants()); + } + List ext = externalVariants.get(typeId); + if (ext != null) { + result.addAll(ext); + } + return result; + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java index 47e03f10d..57f0cbf17 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityEffect.java @@ -38,6 +38,13 @@ public class AbilityEffect { return potionId; } + public static String[] getLangKeys() { + EffectType[] types = values(); + String[] keys = new String[types.length]; + for (int i = 0; i < types.length; i++) keys[i] = types[i].langKey; + return keys; + } + public static EffectType fromOrdinal(int ordinal) { EffectType[] values = values(); if (ordinal >= 0 && ordinal < values.length) { diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java index 0611a0274..af1bd8d30 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityPhase.java @@ -4,5 +4,6 @@ public enum AbilityPhase { IDLE, // Not executing WINDUP, // Charging up (telegraph visible) ACTIVE, // Executing (damage happens) - DAZED // Stunned after interrupt during WINDUP (cannot attack) + DAZED, // Stunned after interrupt during WINDUP (cannot attack) + BURST_DELAY // Waiting between burst repetitions (free movement/rotation) } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java new file mode 100644 index 000000000..797e6b20b --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AbilityVariant.java @@ -0,0 +1,54 @@ +package kamkeel.npcs.controllers.data.ability; + +import java.util.function.Consumer; + +/** + * Represents a variant/template for an ability type. + * When a user creates an ability that has registered variants, + * they are presented with a selection dialog before the ability is created. + * + * Each variant has a display name (lang key) and a configurator that + * applies preset values to the newly created ability. + */ +public class AbilityVariant { + + private final String displayKey; + private final String group; + private final Consumer configurator; + + /** + * @param displayKey Lang key for the variant display name (e.g., "ability.variant.dual") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, Consumer configurator) { + this(displayKey, null, configurator); + } + + /** + * @param displayKey Lang key for the variant display name + * @param group Optional group header shown in the variant selection GUI (e.g., "DBC Addon") + * @param configurator Lambda that configures the ability with preset values + */ + public AbilityVariant(String displayKey, String group, Consumer configurator) { + this.displayKey = displayKey; + this.group = group; + this.configurator = configurator; + } + + public String getDisplayKey() { + return displayKey; + } + + public String getGroup() { + return group; + } + + /** + * Apply this variant's preset configuration to the given ability. + */ + public void apply(Ability ability) { + if (configurator != null) { + configurator.accept(ability); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java b/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java index 01100c318..1c308493c 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/AnchorPoint.java @@ -45,4 +45,17 @@ public enum AnchorPoint { } return names; } + + @Override + public String toString() { + switch (this) { + case FRONT: return "ability.anchor.front"; + case CENTER: return "ability.anchor.center"; + case RIGHT_HAND: return "ability.anchor.rightHand"; + case LEFT_HAND: return "ability.anchor.leftHand"; + case ABOVE_HEAD: return "ability.anchor.aboveHead"; + case CHEST: return "ability.anchor.chest"; + default: return name(); + } + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java b/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java index 69151291f..904fad0b9 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/BuiltInAbility.java @@ -31,14 +31,6 @@ public abstract class BuiltInAbility extends Ability { return registryKey; } - /** - * Built-in abilities are not customizable. - */ - @Override - public boolean isCustomizable() { - return false; - } - /** * Built-in abilities do not write type-specific NBT (they have fixed configs). */ diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java new file mode 100644 index 000000000..9a7f353c1 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityDamageHandler.java @@ -0,0 +1,27 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.EntityLivingBase; + +/** + * External damage handler for abilities. + * When registered, called AFTER script events but BEFORE default attackEntityFrom. + * If handleDamage returns true, default damage is skipped. + */ +public interface IAbilityDamageHandler { + /** + * Handle damage from an ability. + * + * @param ability The ability dealing damage + * @param caster The entity executing the ability + * @param target The entity being hit + * @param damage The damage amount (after script event modifications) + * @param knockback The horizontal knockback + * @param knockbackUp The vertical knockback + * @param knockbackDirX The X component of knockback direction + * @param knockbackDirZ The Z component of knockback direction + * @return true if damage was handled (skip default), false to use default damage + */ + boolean handleDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target, + float damage, float knockback, float knockbackUp, + double knockbackDirX, double knockbackDirZ); +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityFieldProvider.java b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityFieldProvider.java new file mode 100644 index 000000000..f196b307b --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/IAbilityFieldProvider.java @@ -0,0 +1,25 @@ +package kamkeel.npcs.controllers.data.ability; + +import noppes.npcs.client.gui.builder.FieldDef; + +import java.util.List; + +/** + * External field definition provider for abilities. + * Called during getAllDefinitions() to allow mods to inject custom tabs/fields + * into the ability configuration GUI. + *

+ * Note: Although this interface references FieldDef (client-only), it is safe to + * register on both sides because the generic type is erased at bytecode level. + * The addFieldDefinitions method is only ever called from client-side GUI code. + */ +public interface IAbilityFieldProvider { + /** + * Add field definitions to the ability's GUI. + * Fields added here should use .tab() to assign them to a custom tab. + * + * @param ability The ability being configured + * @param defs The mutable list of field definitions to add to + */ + void addFieldDefinitions(Ability ability, List defs); +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/LockType.java b/src/main/java/kamkeel/npcs/controllers/data/ability/LockType.java new file mode 100644 index 000000000..904a6c876 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/LockType.java @@ -0,0 +1,47 @@ +package kamkeel.npcs.controllers.data.ability; + +/** + * Defines what an ability locks when Lock Position is enabled. + */ +public enum LockType { + MOVEMENT, + ROTATION, + BOTH; + + public boolean locksMovement() { + return this == MOVEMENT || this == BOTH; + } + + public boolean locksRotation() { + return this == ROTATION || this == BOTH; + } + + public String getDisplayKey() { + switch (this) { + case MOVEMENT: + return "ability.lockType.movement"; + case ROTATION: + return "ability.lockType.rotation"; + case BOTH: + return "ability.lockType.both"; + default: + return "ability.lockType.both"; + } + } + + public static String[] getDisplayKeys() { + return new String[]{ + "ability.lockType.movement", + "ability.lockType.rotation", + "ability.lockType.both" + }; + } + + public static LockType fromOrdinal(int ordinal) { + LockType[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return BOTH; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java b/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java new file mode 100644 index 000000000..77fae9774 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/PreviewEntityHandler.java @@ -0,0 +1,13 @@ +package kamkeel.npcs.controllers.data.ability; + +import net.minecraft.entity.Entity; + +/** + * Interface for routing entity spawn/kill calls during preview mode. + * In preview mode, entities are not added to the world but instead + * tracked by the GUI for rendering in the 3D viewport. + */ +public interface PreviewEntityHandler { + void onEntitySpawned(Entity entity); + void onEntityRemoved(Entity entity); +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java new file mode 100644 index 000000000..e1142b571 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/RotationMode.java @@ -0,0 +1,53 @@ +package kamkeel.npcs.controllers.data.ability; + +/** + * Defines what happens to NPC rotation during ability phases. + * Used with a LockMovementType to control WHEN it applies. + */ +public enum RotationMode { + /** + * NPC rotates normally via AI look helper. + */ + FREE, + + /** + * Freeze rotation at the moment the phase starts. + * NPC stays facing the direction it was looking when the phase began. + */ + LOCKED, + + /** + * Force NPC to continuously face its target (hit scan). + * Overrides AI look helper every tick for precise aiming. + */ + TRACK; + + public String getDisplayKey() { + switch (this) { + case FREE: + return "ability.rotation.free"; + case LOCKED: + return "ability.rotation.locked"; + case TRACK: + return "ability.rotation.track"; + default: + return "ability.rotation.free"; + } + } + + public static String[] getDisplayKeys() { + return new String[]{ + "ability.rotation.free", + "ability.rotation.locked", + "ability.rotation.track" + }; + } + + public static RotationMode fromOrdinal(int ordinal) { + RotationMode[] values = values(); + if (ordinal >= 0 && ordinal < values.length) { + return values[ordinal]; + } + return FREE; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/TargetingMode.java b/src/main/java/kamkeel/npcs/controllers/data/ability/TargetingMode.java index bd1bb6a47..9bdbdac6f 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/TargetingMode.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/TargetingMode.java @@ -22,5 +22,16 @@ public enum TargetingMode { /** * AOE centered on target */ - AOE_TARGET + AOE_TARGET; + + @Override + public String toString() { + switch (this) { + case AGGRO_TARGET: return "ability.target.aggro_target"; + case SELF: return "ability.target.self"; + case AOE_SELF: return "ability.target.aoe_self"; + case AOE_TARGET: return "ability.target.aoe_target"; + default: return name(); + } + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java index 66983f89b..2187802a5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyAnchorData.java @@ -2,8 +2,9 @@ package kamkeel.npcs.controllers.data.ability.data; import kamkeel.npcs.controllers.data.ability.AnchorPoint; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyAnchorData; -public class EnergyAnchorData { +public class EnergyAnchorData implements IEnergyAnchorData { public AnchorPoint anchorPoint = AnchorPoint.FRONT; public float anchorOffsetX = 0; public float anchorOffsetY = 0; @@ -34,6 +35,54 @@ public class EnergyAnchorData { this.anchorOffsetZ = anchorOffsetZ; } + public AnchorPoint getAnchorPoint() { + return anchorPoint; + } + + public void setAnchorPoint(AnchorPoint anchorPoint) { + this.anchorPoint = anchorPoint; + } + + @Override + public int getAnchor() { + return anchorPoint.ordinal(); + } + + @Override + public void setAnchor(int anchor) { + this.anchorPoint = AnchorPoint.fromOrdinal(anchor); + } + + @Override + public float getAnchorOffsetX() { + return anchorOffsetX; + } + + @Override + public void setAnchorOffsetX(float anchorOffsetX) { + this.anchorOffsetX = anchorOffsetX; + } + + @Override + public float getAnchorOffsetY() { + return anchorOffsetY; + } + + @Override + public void setAnchorOffsetY(float anchorOffsetY) { + this.anchorOffsetY = anchorOffsetY; + } + + @Override + public float getAnchorOffsetZ() { + return anchorOffsetZ; + } + + @Override + public void setAnchorOffsetZ(float anchorOffsetZ) { + this.anchorOffsetZ = anchorOffsetZ; + } + public void writeNBT(NBTTagCompound nbt) { nbt.setInteger("anchorPoint", anchorPoint.ordinal()); nbt.setFloat("anchorOffsetX", anchorOffsetX); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyColorData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyColorData.java deleted file mode 100644 index 4bd841742..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyColorData.java +++ /dev/null @@ -1,50 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.data; - -import net.minecraft.nbt.NBTTagCompound; - -/** - * Groups visual color properties shared by all energy abilities. - * Used as a parameter object for entity constructors and ability configuration. - */ -public class EnergyColorData { - public int innerColor = 0xFFFFFF; - public int outerColor = 0x8888FF; - public boolean outerColorEnabled = true; - public float outerColorWidth = 0.4f; - public float outerColorAlpha = 0.5f; - public float rotationSpeed = 4.0f; - - public EnergyColorData() {} - - public EnergyColorData(int innerColor, int outerColor, boolean outerColorEnabled, - float outerColorWidth, float outerColorAlpha, float rotationSpeed) { - this.innerColor = innerColor; - this.outerColor = outerColor; - this.outerColorEnabled = outerColorEnabled; - this.outerColorWidth = outerColorWidth; - this.outerColorAlpha = outerColorAlpha; - this.rotationSpeed = rotationSpeed; - } - - public void writeNBT(NBTTagCompound nbt) { - nbt.setInteger("innerColor", innerColor); - nbt.setInteger("outerColor", outerColor); - nbt.setBoolean("outerColorEnabled", outerColorEnabled); - nbt.setFloat("outerColorWidth", outerColorWidth); - nbt.setFloat("outerColorAlpha", outerColorAlpha); - nbt.setFloat("rotationSpeed", rotationSpeed); - } - - public void readNBT(NBTTagCompound nbt) { - innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF; - outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF; - outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled"); - outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f; - outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f; - rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; - } - - public EnergyColorData copy() { - return new EnergyColorData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed); - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java index fa09645a6..52f5368f0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyCombatData.java @@ -1,12 +1,13 @@ package kamkeel.npcs.controllers.data.ability.data; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyCombatData; /** * Groups combat properties shared by energy projectile abilities. * Used as a parameter object for entity constructors and ability configuration. */ -public class EnergyCombatData { +public class EnergyCombatData implements IEnergyCombatData { public float damage = 7.0f; public float knockback = 1.0f; public float knockbackUp = 0.1f; @@ -26,6 +27,66 @@ public class EnergyCombatData { this.explosionDamageFalloff = explosionDamageFalloff; } + @Override + public float getDamage() { + return damage; + } + + @Override + public void setDamage(float damage) { + this.damage = damage; + } + + @Override + public float getKnockback() { + return knockback; + } + + @Override + public void setKnockback(float knockback) { + this.knockback = knockback; + } + + @Override + public float getKnockbackUp() { + return knockbackUp; + } + + @Override + public void setKnockbackUp(float knockbackUp) { + this.knockbackUp = knockbackUp; + } + + @Override + public boolean isExplosive() { + return explosive; + } + + @Override + public void setExplosive(boolean explosive) { + this.explosive = explosive; + } + + @Override + public float getExplosionRadius() { + return explosionRadius; + } + + @Override + public void setExplosionRadius(float explosionRadius) { + this.explosionRadius = explosionRadius; + } + + @Override + public float getExplosionDamageFalloff() { + return explosionDamageFalloff; + } + + @Override + public void setExplosionDamageFalloff(float explosionDamageFalloff) { + this.explosionDamageFalloff = explosionDamageFalloff; + } + public void writeNBT(NBTTagCompound nbt) { nbt.setFloat("damage", damage); nbt.setFloat("knockback", knockback); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java new file mode 100644 index 000000000..0d91e1012 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyDisplayData.java @@ -0,0 +1,116 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyDisplayData; + +/** + * Groups visual color properties shared by all energy abilities. + * Used as a parameter object for entity constructors and ability configuration. + */ +public class EnergyDisplayData implements IEnergyDisplayData { + public int innerColor = 0xFFFFFF; + public int outerColor = 0x8888FF; + public boolean outerColorEnabled = true; + public float outerColorWidth = 0.4f; + public float outerColorAlpha = 0.5f; + public float rotationSpeed = 4.0f; + + public EnergyDisplayData() {} + + public EnergyDisplayData(int innerColor, int outerColor) { + this.innerColor = innerColor; + this.outerColor = outerColor; + } + + public EnergyDisplayData(int innerColor, int outerColor, boolean outerColorEnabled, + float outerColorWidth, float outerColorAlpha, float rotationSpeed) { + this.innerColor = innerColor; + this.outerColor = outerColor; + this.outerColorEnabled = outerColorEnabled; + this.outerColorWidth = outerColorWidth; + this.outerColorAlpha = outerColorAlpha; + this.rotationSpeed = rotationSpeed; + } + + @Override + public int getInnerColor() { + return innerColor; + } + + @Override + public void setInnerColor(int innerColor) { + this.innerColor = innerColor; + } + + @Override + public int getOuterColor() { + return outerColor; + } + + @Override + public void setOuterColor(int outerColor) { + this.outerColor = outerColor; + } + + @Override + public boolean isOuterColorEnabled() { + return outerColorEnabled; + } + + @Override + public void setOuterColorEnabled(boolean outerColorEnabled) { + this.outerColorEnabled = outerColorEnabled; + } + + @Override + public float getOuterColorWidth() { + return outerColorWidth; + } + + @Override + public void setOuterColorWidth(float outerColorWidth) { + this.outerColorWidth = outerColorWidth; + } + + @Override + public float getOuterColorAlpha() { + return outerColorAlpha; + } + + @Override + public void setOuterColorAlpha(float outerColorAlpha) { + this.outerColorAlpha = outerColorAlpha; + } + + @Override + public float getRotationSpeed() { + return rotationSpeed; + } + + @Override + public void setRotationSpeed(float rotationSpeed) { + this.rotationSpeed = rotationSpeed; + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setInteger("innerColor", innerColor); + nbt.setInteger("outerColor", outerColor); + nbt.setBoolean("outerColorEnabled", outerColorEnabled); + nbt.setFloat("outerColorWidth", outerColorWidth); + nbt.setFloat("outerColorAlpha", outerColorAlpha); + nbt.setFloat("rotationSpeed", rotationSpeed); + } + + public void readNBT(NBTTagCompound nbt) { + innerColor = nbt.hasKey("innerColor") ? nbt.getInteger("innerColor") : 0xFFFFFF; + outerColor = nbt.hasKey("outerColor") ? nbt.getInteger("outerColor") : 0x8888FF; + outerColorEnabled = !nbt.hasKey("outerColorEnabled") || nbt.getBoolean("outerColorEnabled"); + outerColorWidth = nbt.hasKey("outerColorWidth") ? nbt.getFloat("outerColorWidth") : 0.4f; + outerColorAlpha = nbt.hasKey("outerColorAlpha") ? nbt.getFloat("outerColorAlpha") : 0.5f; + rotationSpeed = nbt.hasKey("rotationSpeed") ? nbt.getFloat("rotationSpeed") : 4.0f; + } + + public EnergyDisplayData copy() { + return new EnergyDisplayData(innerColor, outerColor, outerColorEnabled, outerColorWidth, outerColorAlpha, rotationSpeed); + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java index 5b90bafce..1e81882c7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyHomingData.java @@ -1,12 +1,14 @@ package kamkeel.npcs.controllers.data.ability.data; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyHomingData; + /** * Groups homing/movement properties for energy projectile abilities. * Used by Orb, Disc, and Beam (not Laser or Sweeper). */ -public class EnergyHomingData { +public class EnergyHomingData implements IEnergyHomingData { public float speed = 0.5f; public boolean homing = true; public float homingStrength = 0.15f; @@ -21,6 +23,46 @@ public class EnergyHomingData { this.homingRange = homingRange; } + @Override + public float getSpeed() { + return speed; + } + + @Override + public void setSpeed(float speed) { + this.speed = speed; + } + + @Override + public boolean isHoming() { + return homing; + } + + @Override + public void setHoming(boolean homing) { + this.homing = homing; + } + + @Override + public float getHomingStrength() { + return homingStrength; + } + + @Override + public void setHomingStrength(float homingStrength) { + this.homingStrength = homingStrength; + } + + @Override + public float getHomingRange() { + return homingRange; + } + + @Override + public void setHomingRange(float homingRange) { + this.homingRange = homingRange; + } + public void writeNBT(NBTTagCompound nbt) { nbt.setFloat("speed", speed); nbt.setBoolean("homing", homing); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java index f8f0122e8..9e017e2a5 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLifespanData.java @@ -1,12 +1,13 @@ package kamkeel.npcs.controllers.data.ability.data; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyLifespanData; /** * Groups lifespan/range properties for energy projectile abilities. * Used as a parameter object for entity constructors and ability configuration. */ -public class EnergyLifespanData { +public class EnergyLifespanData implements IEnergyLifespanData { public float maxDistance = 30.0f; public int maxLifetime = 200; @@ -17,6 +18,26 @@ public class EnergyLifespanData { this.maxLifetime = maxLifetime; } + @Override + public float getMaxDistance() { + return maxDistance; + } + + @Override + public void setMaxDistance(float maxDistance) { + this.maxDistance = maxDistance; + } + + @Override + public int getMaxLifetime() { + return maxLifetime; + } + + @Override + public void setMaxLifetime(int maxLifetime) { + this.maxLifetime = maxLifetime; + } + public void writeNBT(NBTTagCompound nbt) { nbt.setFloat("maxDistance", maxDistance); nbt.setInteger("maxLifetime", maxLifetime); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java index 30d4ea6d8..00d0eaa96 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyLightningData.java @@ -1,12 +1,13 @@ package kamkeel.npcs.controllers.data.ability.data; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.api.ability.data.IEnergyLightningData; /** * Groups lightning visual effect properties for energy abilities. * Used as a parameter object for entity constructors and ability configuration. */ -public class EnergyLightningData { +public class EnergyLightningData implements IEnergyLightningData { public boolean lightningEffect = false; public float lightningDensity = 0.15f; public float lightningRadius = 0.5f; @@ -22,6 +23,46 @@ public class EnergyLightningData { this.lightningFadeTime = lightningFadeTime; } + @Override + public boolean isLightningEffect() { + return lightningEffect; + } + + @Override + public void setLightningEffect(boolean lightningEffect) { + this.lightningEffect = lightningEffect; + } + + @Override + public float getLightningDensity() { + return lightningDensity; + } + + @Override + public void setLightningDensity(float lightningDensity) { + this.lightningDensity = lightningDensity; + } + + @Override + public float getLightningRadius() { + return lightningRadius; + } + + @Override + public void setLightningRadius(float lightningRadius) { + this.lightningRadius = lightningRadius; + } + + @Override + public int getLightningFadeTime() { + return lightningFadeTime; + } + + @Override + public void setLightningFadeTime(int lightningFadeTime) { + this.lightningFadeTime = lightningFadeTime; + } + public void writeNBT(NBTTagCompound nbt) { nbt.setBoolean("lightningEffect", lightningEffect); nbt.setFloat("lightningDensity", lightningDensity); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java new file mode 100644 index 000000000..7cc15a706 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/EnergyTrajectoryData.java @@ -0,0 +1,288 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.Constants; +import noppes.npcs.api.IPos; +import noppes.npcs.api.ability.data.IEnergyTrajectoryData; +import noppes.npcs.scripted.NpcAPI; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.BiConsumer; + +public class EnergyTrajectoryData implements IEnergyTrajectoryData { + public int currentPath = 0; + private final List trajectory = new ArrayList<>(); + + public EnergyTrajectoryData() {} + + public EnergyTrajectoryData(int startingPath, Path... paths) { + trajectory.addAll(Arrays.asList(paths)); + this.currentPath = startingPath < trajectory.size() && startingPath >= 0 ? startingPath : 0; + } + + @Override + public int getCurrentPath() { + return currentPath; + } + + @Override + public void setCurrentPath(int currentPath) { + this.currentPath = currentPath; + } + + @Override + public int getDelay(int path) { + if (getPath(path) == null) return -1; + return getPath(path).getDelay(); + } + + @Override + public void setDelay(int path, int ticks) { + if (getPath(path) == null) return; + getPath(path).setDelay(ticks); + } + + @Override + public IPos getPos(int path) { + IPath p = getPath(path); + return p == null ? null : p.getPos(); + } + + @Override + public void setPos(int path, IPos pos) { + IPath p = getPath(path); + if (p != null) p.setPos(pos); + } + + @Override + public boolean isConcluded(int path) { + IPath p = getPath(path); + return p != null && p.isConcluded(); + } + + @Override + public void setConcluded(int path, boolean concluded) { + IPath p = getPath(path); + if (p != null) p.setConcluded(concluded); + } + + @Override + public double getX(int path) { + IPath p = getPath(path); + return p == null ? 0 : p.getX(); + } + + @Override + public double getY(int path) { + IPath p = getPath(path); + return p == null ? 0 : p.getY(); + } + + @Override + public double getZ(int path) { + IPath p = getPath(path); + return p == null ? 0 : p.getZ(); + } + @Override + public void setX(int path, double x) { + IPath p = getPath(path); + if (p != null) p.setX(x); + } + + @Override + public void setY(int path, double y) { + IPath p = getPath(path); + if (p != null) p.setY(y); + } + + @Override + public void setZ(int path, double z) { + IPath p = getPath(path); + if (p != null) p.setZ(z); + } + + public IPath getPath(int path) { + if (path < 0 || path >= trajectory.size()) return null; + return trajectory.get(path); + } + + @Override + public void setPath(int path, IPos pos) { + setPath(path, pos, 0); + } + + @Override + public void setPath(int path, IPos pos, int delay) { + setPath(path, pos.getX(), pos.getY(), pos.getZ(), delay); + } + + @Override + public void setPath(int path, double x, double y, double z) { + setPath(path, x, y, z, 0); + } + + @Override + public void setPath(int path, double x, double y, double z, int delay) { + Path newPath = new Path( + NpcAPI.Instance().getIPos(x, y, z), + delay + ); + + while (trajectory.size() <= path) { + trajectory.add(null); + } + + trajectory.set(path, newPath); + } + + @Override + public IPath createPath(IPos pos) { + return new Path(pos, 0); + } + + @Override + public IPath createPath(IPos pos, int delay) { + return new Path(pos, delay); + } + + @Override + public IPath createPath(double x, double y, double z) { + return createPath(x, y, z, 0); + } + + @Override + public IPath createPath(double x, double y, double z, int delay) { + return new Path(NpcAPI.Instance().getIPos(x, y, z), delay); + } + + @Override + public void forEach(BiConsumer lambda) { + for (int i = 0; i < trajectory.size(); i++) { + lambda.accept(i, trajectory.get(i)); + } + } + + public int size() { + return trajectory.size(); + } + + public boolean isEmpty() { + return trajectory.isEmpty(); + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setInteger("currentPath", currentPath); + + for (int i = 0; i < trajectory.size(); i++) { + Path path = trajectory.get(i); + NBTTagCompound pathNbt = new NBTTagCompound(); + path.writeNBT(pathNbt); + nbt.setTag("Path_" + i, pathNbt); + } + } + + public void readNBT(NBTTagCompound nbt) { + this.currentPath = nbt.hasKey("currentPath") ? nbt.getInteger("currentPath") : 0; + + int i = 0; + while (nbt.hasKey("Path_" + i, Constants.NBT.TAG_COMPOUND)) { + NBTTagCompound pathNbt = nbt.getCompoundTag("Path_" + i); + Path path = (Path) createPath(0, 0, 0); + path.readNBT(pathNbt); + trajectory.add(path); + i++; + } + } + + public static class Path implements IEnergyTrajectoryData.IPath{ + public IPos pos; + public int delayTicks; + public boolean concluded; + + public Path(IPos pos, int delayTicks) { + this.pos = pos; + this.delayTicks = delayTicks; + } + + @Override + public IPos getPos() { + return pos; + } + + @Override + public void setPos(IPos pos) { + this.pos = pos; + } + + @Override + public int getDelay() { + return delayTicks; + } + + @Override + public void setDelay(int delayTicks) { + this.delayTicks = delayTicks; + } + + @Override + public boolean isConcluded() { + return concluded; + } + + @Override + public void setConcluded(boolean concluded) { + this.concluded = concluded; + } + + @Override + public double getX() { + return pos.getX(); + } + + @Override + public void setX(double x) { + this.pos = NpcAPI.Instance().getIPos(x, getY(), getZ()); + } + + @Override + public double getY() { + return pos.getY(); + } + + @Override + public void setY(double y) { + this.pos = NpcAPI.Instance().getIPos(getX(), y, getZ()); + } + + @Override + public double getZ() { + return pos.getZ(); + } + + @Override + public void setZ(double z) { + this.pos = NpcAPI.Instance().getIPos(pos.getX(), pos.getY(), z); + } + + public void writeNBT(NBTTagCompound nbt) { + nbt.setInteger("delay", delayTicks); + nbt.setBoolean("concluded", concluded); + nbt.setDouble("X", getX()); + nbt.setDouble("Y", getY()); + nbt.setDouble("Z", getZ()); + } + + public void readNBT(NBTTagCompound nbt) { + this.delayTicks = nbt.hasKey("delay") ? nbt.getInteger("delay") : 0; + this.concluded = nbt.hasKey("concluded") && nbt.getBoolean("concluded"); + + double x = nbt.getDouble("X"); + double y = nbt.getDouble("Y"); + double z = nbt.getDouble("Z"); + + this.pos = NpcAPI.Instance().getIPos(x, y, z); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java new file mode 100644 index 000000000..49ee50f7e --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/data/ProjectileData.java @@ -0,0 +1,60 @@ +package kamkeel.npcs.controllers.data.ability.data; + +import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import net.minecraft.nbt.NBTTagCompound; + +/** + * Per-projectile data: anchor point + optional color override. + * All projectiles share the primary EnergyDisplayData; this class + * allows individual projectiles to override just the inner/outer colors. + */ +public class ProjectileData { + public EnergyAnchorData anchor; + public boolean colorOverride = false; + public int innerColor = 0xFFFFFF; + public int outerColor = 0x8888FF; + + public ProjectileData(AnchorPoint defaultAnchor) { + this.anchor = new EnergyAnchorData(defaultAnchor); + } + + /** + * Returns the display data to use for this projectile. + * If colorOverride is false, returns the primary display data directly. + * If colorOverride is true, returns a copy with overridden inner/outer colors. + */ + public EnergyDisplayData resolveDisplay(EnergyDisplayData primary) { + if (!colorOverride) return primary; + EnergyDisplayData resolved = primary.copy(); + resolved.innerColor = this.innerColor; + resolved.outerColor = this.outerColor; + return resolved; + } + + public void writeNBT(NBTTagCompound nbt) { + anchor.writeNBT(nbt); + nbt.setBoolean("colorOverride", colorOverride); + if (colorOverride) { + nbt.setInteger("overrideInnerColor", innerColor); + nbt.setInteger("overrideOuterColor", outerColor); + } + } + + public void readNBT(NBTTagCompound nbt) { + anchor.readNBT(nbt); + colorOverride = nbt.getBoolean("colorOverride"); + if (colorOverride) { + innerColor = nbt.hasKey("overrideInnerColor") ? nbt.getInteger("overrideInnerColor") : 0xFFFFFF; + outerColor = nbt.hasKey("overrideOuterColor") ? nbt.getInteger("overrideOuterColor") : 0x8888FF; + } + } + + public ProjectileData copy() { + ProjectileData copy = new ProjectileData(anchor.anchorPoint); + copy.anchor = anchor.copy(); + copy.colorOverride = colorOverride; + copy.innerColor = innerColor; + copy.outerColor = outerColor; + return copy; + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java new file mode 100644 index 000000000..5edd0a718 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldBuilder.java @@ -0,0 +1,180 @@ +package kamkeel.npcs.controllers.data.ability.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.builder.FieldType; +import noppes.npcs.client.gui.builder.GuiFieldBuilder; +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.GuiNpcTextField; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Ability-specific extension of {@link GuiFieldBuilder} that handles + * the EFFECTS_LIST field type. + */ +@SideOnly(Side.CLIENT) +public class AbilityFieldBuilder extends GuiFieldBuilder { + + // Effects list metadata: widgetId -> [effectIndex, action] + // action: 0=type, 1=duration(text), 2=amp, 3=delete, 4=add + private final Map effectWidgetMeta = new HashMap<>(); + + public AbilityFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { + super(parent, fontRenderer); + } + + @Override + protected int build(List fields) { + effectWidgetMeta.clear(); + return super.build(fields); + } + + @Override + protected int buildField(FieldDef def, int y, List fields, int index) { + if (def.getType() == FieldType.EFFECTS_LIST) { + return renderEffectsList(def, y); + } + return -1; // not handled + } + + @SuppressWarnings("unchecked") + private int renderEffectsList(FieldDef def, int y) { + // Section header + y += 3; + sw.addLabel(new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55)); + y += 15; + + List effects = (List) def.getValue(); + if (effects == null) effects = new ArrayList<>(); + + String[] typeNames = AbilityEffect.EffectType.getLangKeys(); + String[] ampValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; + + for (int e = 0; e < effects.size() && e < 5; e++) { + AbilityEffect effect = effects.get(e); + + // Type selector button + int typeIdx = effect.getType().ordinal(); + GuiNpcButton typeBtn = new GuiNpcButton(widgetId, colLLabel, y, 100, 20, typeNames, typeIdx); + sw.addButton(typeBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 0}); + widgetId++; + + // Duration text field + GuiNpcTextField durField = new GuiNpcTextField(widgetId, parent, fontRenderer, + colLLabel + 104, y, 50, 20, String.valueOf(effect.getDurationTicks())); + durField.setIntegersOnly(); + durField.setMinMaxDefault(1, 12000, 60); + sw.addTextField(durField); + textFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 1}); + widgetId++; + + // Amplifier selector (0-10) + GuiNpcButton ampBtn = new GuiNpcButton(widgetId, colLLabel + 158, y, 40, 20, ampValues, effect.getAmplifier()); + sw.addButton(ampBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{e, 2}); + widgetId++; + + // Delete button + GuiNpcButton delBtn = new GuiNpcButton(clearId, colLLabel + 202, y, 20, 20, "X"); + sw.addButton(delBtn); + clearFieldMap.put(clearId, def); + effectWidgetMeta.put(clearId, new int[]{e, 3}); + clearId++; + + y += rowHeight; + } + + // Add button (if < 5 effects) + if (effects.size() < 5) { + GuiNpcButton addBtn = new GuiNpcButton(widgetId, colLLabel, y, 50, 20, "gui.add"); + sw.addButton(addBtn); + buttonFieldMap.put(widgetId, def); + effectWidgetMeta.put(widgetId, new int[]{effects.size(), 4}); + widgetId++; + clearId++; + y += rowHeight; + } + + return y; + } + + // ═══════════════════════════════════════════════════════════════════ + // EVENT HANDLING OVERRIDES + // ═══════════════════════════════════════════════════════════════════ + + @Override + @SuppressWarnings("unchecked") + public boolean handleButtonEvent(int buttonId, GuiButton button) { + // Check effects list buttons via metadata + int[] meta = effectWidgetMeta.get(buttonId); + if (meta != null) { + FieldDef def = buttonFieldMap.get(buttonId); + if (def == null) def = clearFieldMap.get(buttonId); + if (def != null && def.getType() == FieldType.EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects == null) return false; + int effectIdx = meta[0]; + int action = meta[1]; + + switch (action) { + case 0: // Type changed + if (effectIdx < effects.size()) { + effects.get(effectIdx).setType(AbilityEffect.EffectType.fromOrdinal(((GuiNpcButton) button).getValue())); + } + return true; + case 2: // Amp changed + if (effectIdx < effects.size()) { + effects.get(effectIdx).setAmplifier(((GuiNpcButton) button).getValue()); + } + return true; + case 3: // Delete + if (effectIdx < effects.size()) { + effects.remove(effectIdx); + } + return true; + case 4: // Add + if (effects.size() < 5) { + effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0)); + } + return true; + } + } + } + + return super.handleButtonEvent(buttonId, button); + } + + @Override + @SuppressWarnings("unchecked") + public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { + int[] meta = effectWidgetMeta.get(textFieldId); + if (meta != null && meta[1] == 1) { // duration field + FieldDef def = textFieldMap.get(textFieldId); + if (def != null && def.getType() == FieldType.EFFECTS_LIST) { + List effects = (List) def.getValue(); + if (effects != null && meta[0] < effects.size()) { + effects.get(meta[0]).setDurationTicks(field.getInteger()); + } + return true; + } + } + + return super.handleTextFieldEvent(textFieldId, field); + } + + public Map getEffectWidgetMeta() { return effectWidgetMeta; } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java new file mode 100644 index 000000000..6e419b943 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/gui/AbilityFieldDefs.java @@ -0,0 +1,27 @@ +package kamkeel.npcs.controllers.data.ability.gui; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import kamkeel.npcs.controllers.data.ability.AbilityEffect; +import noppes.npcs.client.gui.builder.FieldDef; +import noppes.npcs.client.gui.builder.FieldType; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Ability-specific FieldDef factories. These create FieldDef instances + * with types that require ability-specific rendering (e.g. EFFECTS_LIST). + */ +@SideOnly(Side.CLIENT) +public class AbilityFieldDefs { + + @SuppressWarnings("unchecked") + public static FieldDef effectsListField(String label, Supplier> getter, Consumer> setter) { + return FieldDef.custom(label, FieldType.EFFECTS_LIST, + () -> getter.get(), + v -> setter.accept((List) v)); + } + +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java new file mode 100644 index 000000000..f99a03528 --- /dev/null +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityBeam.java @@ -0,0 +1,637 @@ +package kamkeel.npcs.controllers.data.ability.type; + +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.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.RotationMode; +import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.controllers.data.telegraph.Telegraph; +import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; +import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import kamkeel.npcs.entity.EntityAbilityBeam; +import kamkeel.npcs.util.AnchorPointHelper; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import noppes.npcs.api.ability.type.IAbilityEnergyBeam; + +import java.util.Arrays; +import java.util.List; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; + +/** + * Energy Beam ability: A homing head with a trailing path. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. + */ +public class AbilityBeam extends Ability implements IAbilityEnergyBeam { + + private static final int MAX_PROJECTILES = 8; + + // Beam shape properties (shared) + private float beamWidth = 0.4f; + private float headSize = 0.6f; + + // Projectile count and fire stagger + private int projectileCount = 1; + private int fireDelay = 0; + + // Shared visual data (all projectiles use these) + private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f); + private EnergyLightningData lightningData = new EnergyLightningData(); + private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + + // Shared combat/movement data + private final EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f); + private final EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f); + private final EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); + + // Per-projectile data (anchor + optional color override) + private ProjectileData[] projectiles; + + // Transient entity state + private transient EntityAbilityBeam[] beamEntities; + + public AbilityBeam() { + this.typeId = "ability.cnpc.beam"; + this.name = "Beam"; + this.targetingMode = TargetingMode.AGGRO_TARGET; + this.maxRange = 20.0f; + this.minRange = 5.0f; + this.cooldownTicks = 0; + this.windUpTicks = 40; + this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.TRACK; + this.rotationPhase = LockMovementType.WINDUP_AND_ACTIVE; + this.telegraphType = TelegraphType.CIRCLE; + this.showTelegraph = true; + this.windUpAnimationName = "Ability_Beam_Windup"; + this.activeAnimationName = "Ability_Beam_Active"; + initProjectiles(1); + } + + private void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + private AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; + default: return AnchorPoint.FRONT; + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { + return projectileCount; + } + + public int getFireDelay() { + return fireDelay; + } + + public void setFireDelay(int delay) { + this.fireDelay = Math.max(0, delay); + } + + // Legacy compat + public int getDualFireDelay() { return fireDelay; } + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Beam"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityBeam beam = (AbilityBeam) a; + a.setName("Dual Beam"); + beam.setProjectileCount(2); + beam.setFireDelay(0); + // Set color override for second beam + beam.projectiles[1].colorOverride = true; + beam.projectiles[1].innerColor = 0xFFFFFF; + beam.projectiles[1].outerColor = 0xFF0000; + a.setWindUpTicks(80); + a.setWindUpAnimationName("Ability_BeamDual_Windup"); + a.setActiveAnimationName("Ability_BeamDual_Active"); + }) + ); + } + + @Override + public boolean allowOverlap() { + return true; + } + + @Override + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); + } + + @Override + public boolean isTargetingModeLocked() { + return true; + } + + @Override + public TargetingMode[] getAllowedTargetingModes() { + return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + } + + /** + * Create beam entities. + * NPC: target is the aggro target — beams will home toward it. + * Player: target is null — beams fire in caster's look direction. + */ + private EntityAbilityBeam[] createBeamEntities(EntityLivingBase caster, EntityLivingBase target, World world) { + EntityAbilityBeam[] entities = new EntityAbilityBeam[projectileCount]; + float offsetDist = 1.0f; + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor, offsetDist); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + entities[i] = new EntityAbilityBeam( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + beamWidth, headSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + lockMovement.locksActive()); + entities[i].setEffects(this.effects); + entities[i].setSourceAbility(this); + } + if (projectileCount == 2 && entities[0] != null && entities[1] != null) { + entities[0].setSiblingEntityId(entities[1].getEntityId()); + entities[1].setSiblingEntityId(entities[0].getEntityId()); + } + return entities; + } + + private void fireBeamEntity(EntityAbilityBeam beam, EntityLivingBase target) { + if (beam == null || beam.isDead) return; + if (isPreview()) { + beam.startPreviewFiring(); + } else { + beam.startFiring(target); + } + } + + @Override + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + if (world.isRemote && !isPreview()) return; + + if (tick == 1) { + beamEntities = createBeamEntities(caster, target, world); + float offsetDist = 1.0f; + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + beamEntities[i].setupPreview(caster, beamWidth, headSize, resolved, lightningData, projectiles[i].anchor, windUpTicks, offsetDist); + } else { + beamEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, offsetDist); + } + spawnAbilityEntity(world, beamEntities[i]); + } + } + } + + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + beamEntities = createBeamEntities(caster, target, world); + for (EntityAbilityBeam beam : beamEntities) { + spawnAbilityEntity(world, beam); + } + for (EntityAbilityBeam beam : beamEntities) { + fireBeamEntity(beam, target); + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + if (world.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (beamEntities == null) return; + + fireBeamEntity(beamEntities[0], target); + + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireBeamEntity(beamEntities[i], target); + } + } + } + + @Override + public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + if (beamEntities == null) { + signalCompletion(); + return; + } + + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireBeamEntity(beamEntities[i], target); + } + } + } + + boolean allDead = true; + for (EntityAbilityBeam beam : beamEntities) { + if (beam != null && !beam.isDead) { + allDead = false; + break; + } + } + if (allDead) { + signalCompletion(); + } + } + + @Override + public void onComplete(EntityLivingBase caster, EntityLivingBase target) { + } + + @Override + public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { + cleanup(); + } + + @Override + public void cleanup() { + if (beamEntities != null) { + for (int i = 0; i < beamEntities.length; i++) { + if (beamEntities[i] != null && !beamEntities[i].isDead) { + beamEntities[i].setDead(); + } + beamEntities[i] = null; + } + } + beamEntities = null; + } + + @Override + public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { + // NPC: telegraph on aggro target position + // Player: no telegraph (beam fires in look direction, no fixed position to mark) + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { + return null; + } + + Telegraph telegraph = Telegraph.circle(headSize * 2.0f); + telegraph.setDurationTicks(windUpTicks); + telegraph.setColor(windUpColor); + telegraph.setWarningColor(activeColor); + telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); + telegraph.setHeightOffset(telegraphHeightOffset); + + TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); + instance.setCasterEntityId(caster.getEntityId()); + instance.setEntityIdToFollow(target.getEntityId()); + + return instance; + } + + @Override + public float getTelegraphRadius() { + return headSize * 2.0f; + } + + @Override + public void writeTypeNBT(NBTTagCompound nbt) { + nbt.setFloat("beamWidth", beamWidth); + nbt.setFloat("headSize", headSize); + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared visual data + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + + // Shared combat/movement data + combatData.writeNBT(nbt); + homingData.writeNBT(nbt); + lifespanData.writeNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } + } + + @Override + public void readTypeNBT(NBTTagCompound nbt) { + this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; + this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; + + int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + initProjectiles(count); + + if (nbt.hasKey("fireDelay")) { + this.fireDelay = nbt.getInteger("fireDelay"); + } else if (nbt.hasKey("dualFireDelay")) { + this.fireDelay = nbt.getInteger("dualFireDelay"); + } else { + this.fireDelay = 0; + } + + combatData.readNBT(nbt); + homingData.readNBT(nbt); + lifespanData.readNBT(nbt); + + if (nbt.hasKey("Projectile_0")) { + NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); + if (proj0.hasKey("colorOverride")) { + // NEW format + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } else { + // OLD per-projectile format + displayData.readNBT(proj0); + lightningData.readNBT(proj0); + projectiles[0].anchor.readNBT(proj0); + + for (int i = 1; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); + projectiles[i].anchor.readNBT(projNbt); + + EnergyDisplayData tempDisplay = new EnergyDisplayData(); + tempDisplay.readNBT(projNbt); + if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { + projectiles[i].colorOverride = true; + projectiles[i].innerColor = tempDisplay.innerColor; + projectiles[i].outerColor = tempDisplay.outerColor; + } + } + } + } + } else { + // LEGACY flat format + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + projectiles[0].anchor.readNBT(nbt); + } + } + + // ═══════════════════════════════════════════════════════════════════ + // API GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public float getBeamWidth() { return beamWidth; } + public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } + + public float getHeadSize() { return headSize; } + public void setHeadSize(float headSize) { this.headSize = headSize; } + + public float getSpeed() { return homingData.speed; } + public void setSpeed(float speed) { this.homingData.speed = speed; } + + public float getMaxDistance() { return lifespanData.maxDistance; } + public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } + + public int getMaxLifetime() { return lifespanData.maxLifetime; } + public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } + + public float getDamage() { return combatData.damage; } + public void setDamage(float damage) { this.combatData.damage = damage; } + + public float getKnockback() { return combatData.knockback; } + public void setKnockback(float knockback) { this.combatData.knockback = knockback; } + + public float getKnockbackUp() { return combatData.knockbackUp; } + public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } + + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean homing) { this.homingData.homing = homing; } + + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } + + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } + + public boolean isExplosive() { return combatData.explosive; } + public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } + + public float getExplosionRadius() { return combatData.explosionRadius; } + public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } + + public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } + + // Shared display data (primary colors) + public int getInnerColor() { return displayData.innerColor; } + public void setInnerColor(int innerColor) { displayData.innerColor = innerColor; } + + public int getOuterColor() { return displayData.outerColor; } + public void setOuterColor(int outerColor) { displayData.outerColor = outerColor; } + + public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + public void setOuterColorEnabled(boolean outerColorEnabled) { displayData.outerColorEnabled = outerColorEnabled; } + + public float getOuterColorWidth() { return displayData.outerColorWidth; } + public void setOuterColorWidth(float outerColorWidth) { displayData.outerColorWidth = outerColorWidth; } + + public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + public void setOuterColorAlpha(float outerColorAlpha) { displayData.outerColorAlpha = outerColorAlpha; } + + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float rotationSpeed) { displayData.rotationSpeed = rotationSpeed; } + + // Shared lightning data + public boolean hasLightningEffect() { return lightningData.lightningEffect; } + public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; } + + public float getLightningDensity() { return lightningData.lightningDensity; } + public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; } + + public float getLightningRadius() { return lightningData.lightningRadius; } + public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; } + + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int lightningFadeTime) { lightningData.lightningFadeTime = lightningFadeTime; } + + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint anchorPoint) { projectiles[0].anchor.anchorPoint = anchorPoint; } + + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } + + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } + + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } + + @Override + public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } + + @Override + public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; + } + + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; + } + + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } + + private int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); + } + + @Override + public int getMaxPreviewDuration() { + return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; + } + + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) + )); + + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); + defs.add(FieldDef.section("ability.section.beam")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.beamWidth", this::getBeamWidth, this::setBeamWidth), + FieldDef.floatField("ability.headSize", this::getHeadSize, this::setHeadSize) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), + FieldDef.floatField("gui.range", this::getHomingRange, this::setHomingRange).visibleWhen(this::isHoming) + )); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); + + // Visual tab - shared primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Visual tab - shared effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } + } +} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java index 37d88e1f7..4ae81bfcb 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCharge.java @@ -14,13 +14,13 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityCharge; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityCharge; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -58,17 +58,6 @@ public class AbilityCharge extends Ability implements IAbilityCharge { this.activeSound = "mob.zombie.attack"; } - @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityCharge(this, callback); - } - @Override public boolean isTargetingModeLocked() { return true; @@ -98,11 +87,13 @@ public class AbilityCharge extends Ability implements IAbilityCharge { } /** - * Locks the charge direction based on current target position. - * Called once at windup start - direction won't change even if target moves. + * Locks the charge direction. Called once at windup start — direction won't change even if target moves. + * NPC: charges toward aggro target. + * Player: charges in look direction. */ private void lockChargeDirection(EntityLivingBase caster, EntityLivingBase target) { - if (target != null) { + if (!isPlayerCaster(caster) && target != null) { + // NPC: charge toward aggro target double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; double len = Math.sqrt(dx * dx + dz * dz); @@ -113,6 +104,7 @@ public class AbilityCharge extends Ability implements IAbilityCharge { chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); } } else { + // Player: charge in look direction float yaw = (float) Math.toRadians(caster.rotationYaw); chargeDirection = Vec3.createVectorHelper(-Math.sin(yaw), 0, Math.cos(yaw)); } @@ -149,7 +141,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge { if (chargeDirection == null) return; // Enforce rotation every tick - enforceLockedRotation(caster); + if (!isPreview()) { + enforceLockedRotation(caster); + } // Calculate distance traveled double distanceTraveled = Math.sqrt( @@ -161,12 +155,15 @@ public class AbilityCharge extends Ability implements IAbilityCharge { if (distanceTraveled >= maxRange) { caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } signalCompletion(); return; } - if (isChargeBlocked(caster)) { + // Block detection (skip in preview - no real world collision) + if (!isPreview() && isChargeBlocked(caster)) { stopMomentum(caster); signalCompletion(); return; @@ -176,10 +173,12 @@ public class AbilityCharge extends Ability implements IAbilityCharge { caster.motionX = chargeDirection.xCoord * chargeSpeed; caster.motionY = 0; caster.motionZ = chargeDirection.zCoord * chargeSpeed; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } - // Server-side collision damage - if (!world.isRemote) { + // Server-side collision damage (skip in preview) + if (!world.isRemote && !isPreview()) { AxisAlignedBB hitBox = caster.boundingBox.expand(hitWidth, hitWidth * 0.5, hitWidth); @SuppressWarnings("unchecked") @@ -222,7 +221,9 @@ public class AbilityCharge extends Ability implements IAbilityCharge { private void stopMomentum(EntityLivingBase caster) { caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } } private boolean isChargeBlocked(EntityLivingBase caster) { @@ -260,9 +261,10 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return null; } - // Calculate direction to target at this moment (locked) + // NPC: telegraph points toward aggro target + // Player: telegraph points in look direction float yaw; - if (target != null) { + if (!isPlayerCaster(caster) && target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; yaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); @@ -288,66 +290,8 @@ public class AbilityCharge extends Ability implements IAbilityCharge { return instance; } - // ==================== PREVIEW MODE ==================== - - private transient double previewDirX, previewDirZ; - private transient double previewStartX, previewStartZ; - private transient boolean previewCharging = false; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewStartX = npc.posX; - previewStartZ = npc.posZ; - previewCharging = false; - - // Calculate direction toward fake target - if (previewTarget != null) { - double dx = previewTarget.posX - npc.posX; - double dz = previewTarget.posZ - npc.posZ; - double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - previewDirX = dx / len; - previewDirZ = dz / len; - } else { - float yaw = (float) Math.toRadians(npc.rotationYaw); - previewDirX = -Math.sin(yaw); - previewDirZ = Math.cos(yaw); - } - } else { - float yaw = (float) Math.toRadians(npc.rotationYaw); - previewDirX = -Math.sin(yaw); - previewDirZ = Math.cos(yaw); - } - previewCharging = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewCharging) return; - - // Check distance traveled - double distTraveled = Math.sqrt( - Math.pow(npc.posX - previewStartX, 2) + - Math.pow(npc.posZ - previewStartZ, 2) - ); - - if (distTraveled >= maxRange) { - previewCharging = false; - return; - } - - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewDirX * chargeSpeed; - npc.posZ += previewDirZ * chargeSpeed; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return (int) Math.ceil(maxRange / chargeSpeed) + 5; } @@ -405,4 +349,20 @@ public class AbilityCharge extends Ability implements IAbilityCharge { public void setHitWidth(float hitWidth) { this.hitWidth = hitWidth; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("ability.chargeSpeed", this::getChargeSpeed, this::setChargeSpeed) + ), + FieldDef.row( + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth) + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java index ef2d2f687..22831f4ff 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -1,7 +1,5 @@ package kamkeel.npcs.controllers.data.ability.type; -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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; @@ -11,13 +9,17 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityCutter; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilityCutter; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -31,7 +33,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter { public enum SweepMode { SWIPE, - SPIN + SPIN; + + @Override + public String toString() { + switch (this) { + case SWIPE: return "ability.sweep.swipe"; + case SPIN: return "ability.sweep.spin"; + default: return name(); + } + } } private float arcAngle = 90.0f; @@ -61,17 +72,8 @@ public class AbilityCutter extends Ability implements IAbilityCutter { this.telegraphType = TelegraphType.CONE; this.windUpSound = "random.bow"; this.activeSound = "random.break"; - } - - @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityCutter(this, callback); + this.windUpAnimationName = "Ability_Cutter_Windup"; + this.activeAnimationName = "Ability_Cutter_Active"; } @Override @@ -107,32 +109,48 @@ public class AbilityCutter extends Ability implements IAbilityCutter { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; switch (sweepMode) { case SWIPE: + float prevRotation = currentRotation; + currentRotation += sweepSpeed; if (currentRotation > arcAngle / 2.0f) { - signalCompletion(); // Swipe arc complete + if (!isPreview()) { + performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); + } + signalCompletion(); return; } - performSweepDamage(caster, world, innerRadius, range, currentRotation); - currentRotation += sweepSpeed; + if (!isPreview()) { + performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation); + } break; case SPIN: if (tick >= spinDurationTicks) { - signalCompletion(); // Spin duration complete + signalCompletion(); return; } + float prevSpin = currentRotation; currentRotation = (currentRotation + sweepSpeed) % 360.0f; - hitEntities.clear(); - performSweepDamage(caster, world, innerRadius, range, currentRotation); + if (!isPreview()) { + hitEntities.clear(); + performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation); + } break; } } - private void performSweepDamage(EntityLivingBase caster, World world, float minDist, float maxDist, float angleOffset) { - float casterYaw = caster.rotationYaw + angleOffset; + /** + * Check for entities between two sweep angles, ensuring no gaps between ticks. + * For SWIPE mode, this covers the continuous arc from startAngle to endAngle. + */ + private void performSweepDamageRange(EntityLivingBase caster, World world, float minDist, float maxDist, + float startAngle, float endAngle) { + // Calculate the angular range covered this tick + float minAngle = Math.min(startAngle, endAngle); + float maxAngle = Math.max(startAngle, endAngle); AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( caster.posX - maxDist, caster.posY - 1, caster.posZ - maxDist, @@ -153,7 +171,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { double dist = Math.sqrt(dx * dx + dz * dz); if (dist < minDist || dist > maxDist) continue; - if (!isInArc(dx, dz, casterYaw, arcAngle)) continue; + if (!isInSweepRange(dx, dz, caster.rotationYaw, minAngle, maxAngle)) continue; hitEntities.add(entity.getEntityId()); @@ -170,6 +188,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter { } } + /** + * Check if an entity falls within the angular range between two sweep positions. + * This ensures entities at long range can't slip between tick-gaps. + */ + private boolean isInSweepRange(double dx, double dz, float casterYaw, float minAngle, float maxAngle) { + double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); + double entityRelative = normalizeAngle(angleToEntity - casterYaw); + return entityRelative >= minAngle && entityRelative <= maxAngle; + } + private boolean isInArc(double dx, double dz, float casterYaw, float arcWidth) { double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); double angleDiff = normalizeAngle(angleToEntity - casterYaw); @@ -311,4 +339,30 @@ public class AbilityCutter extends Ability implements IAbilityCutter { public float getCurrentRotation() { return currentRotation; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("gui.range", this::getRange, this::setRange) + ), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.section("ability.section.sweep"), + FieldDef.enumField("ability.sweepMode", SweepMode.class, this::getSweepModeEnum, this::setSweepModeEnum) + .hover("ability.hover.sweepMode"), + FieldDef.row( + FieldDef.floatField("ability.arcAngle", this::getArcAngle, this::setArcAngle), + FieldDef.floatField("ability.innerRadius", this::getInnerRadius, this::setInnerRadius) + ), + FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed), + FieldDef.intField("ability.spinDuration", this::getSpinDurationTicks, this::setSpinDurationTicks) + .range(1, 1000) + .visibleWhen(() -> this.getSweepModeEnum() == SweepMode.SPIN), + FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing) + .hover("ability.hover.piercing"), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java index e070b099e..0f8cbe374 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java @@ -12,13 +12,13 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityDash; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.api.ability.type.IAbilityDash; +import java.util.Arrays; +import java.util.List; import java.util.Random; /** @@ -32,7 +32,16 @@ public class AbilityDash extends Ability implements IAbilityDash { */ public enum DashMode { AGGRESSIVE, - DEFENSIVE + DEFENSIVE; + + @Override + public String toString() { + switch (this) { + case AGGRESSIVE: return "ability.dash.aggressive"; + case DEFENSIVE: return "ability.dash.defensive"; + default: return name(); + } + } } /** @@ -78,12 +87,14 @@ public class AbilityDash extends Ability implements IAbilityDash { // Type-specific parameters private DashMode dashMode = DashMode.DEFENSIVE; private float dashDistance = 4.0f; - private float dashSpeed = 1.5f; + private float dashSpeed = 0.5f; // Runtime state private transient Vec3 dashDirection; private transient double startX, startY, startZ; + private transient double prevTickX, prevTickZ; private transient DashDirection chosenDirection; + private transient int maxActiveTicks; public AbilityDash() { this.typeId = "ability.cnpc.dash"; @@ -102,15 +113,8 @@ public class AbilityDash extends Ability implements IAbilityDash { } @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui( - IAbilityConfigCallback callback) { - return new SubGuiAbilityDash(this, callback); + public boolean hasDamage() { + return false; } @Override @@ -133,6 +137,11 @@ public class AbilityDash extends Ability implements IAbilityDash { startX = caster.posX; startY = caster.posY; startZ = caster.posZ; + prevTickX = caster.posX; + prevTickZ = caster.posZ; + + // Safety timeout: expected ticks + generous buffer to prevent infinite dash + maxActiveTicks = dashSpeed > 0 ? (int)(dashDistance / dashSpeed) + 10 : 10; // Choose random direction based on mode DashDirection[] directions = dashMode == DashMode.AGGRESSIVE @@ -140,9 +149,10 @@ public class AbilityDash extends Ability implements IAbilityDash { : DEFENSIVE_DIRECTIONS; chosenDirection = directions[RANDOM.nextInt(directions.length)]; - // Calculate dash direction relative to target + // NPC: dash direction is relative to aggro target facing + // Player: dash direction is relative to look direction float baseYaw; - if (target != null) { + if (!isPlayerCaster(caster) && target != null) { double dx = target.posX - caster.posX; double dz = target.posZ - caster.posZ; baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); @@ -160,63 +170,87 @@ public class AbilityDash extends Ability implements IAbilityDash { Math.cos(yawRad) ); + // Small upward impulse for a skip/hop arc (gravity handles the descent) + caster.motionY = 0.2; } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (dashDirection == null) return; + // Safety timeout or missing state: force-complete to prevent stuck NPC + if (!isPreview() && (dashDirection == null || tick > maxActiveTicks)) { + stopDash(caster); + signalCompletion(); + return; + } - // Calculate distance traveled - double distanceTraveled = Math.sqrt( - Math.pow(caster.posX - startX, 2) + - Math.pow(caster.posZ - startZ, 2) - ); + if (dashDirection == null) { + signalCompletion(); + return; + } + + // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall + if (!isPreview() && tick > 1) { + double dx = caster.posX - prevTickX; + double dz = caster.posZ - prevTickZ; + if (dx * dx + dz * dz < 0.0001) { + stopDash(caster); + signalCompletion(); + return; + } + } + prevTickX = caster.posX; + prevTickZ = caster.posZ; // Check if reached max distance - if (distanceTraveled >= dashDistance) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + double travelDx = caster.posX - startX; + double travelDz = caster.posZ - startZ; + if (travelDx * travelDx + travelDz * travelDz >= (double) dashDistance * dashDistance) { + stopDash(caster); signalCompletion(); return; } - if (isDashBlocked(caster)) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + // Block detection (skip in preview - no real world collision) + if (!isPreview() && isDashBlocked(caster)) { + stopDash(caster); signalCompletion(); return; } - // Move caster + // Move caster (motionY left to gravity for skip arc) caster.motionX = dashDirection.xCoord * dashSpeed; - caster.motionY = 0; caster.motionZ = dashDirection.zCoord * dashSpeed; - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; - // Trail particles - world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + // Trail particles + world.spawnParticle("smoke", caster.posX, caster.posY + 0.5, caster.posZ, 0, 0, 0); + } + } + + private void stopDash(EntityLivingBase caster) { + caster.motionX = 0; + caster.motionZ = 0; + if (!isPreview()) { + caster.velocityChanged = true; + } } @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + stopDash(caster); } @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - caster.motionX = 0; - caster.motionZ = 0; - caster.velocityChanged = true; + stopDash(caster); } @Override public void cleanup() { dashDirection = null; chosenDirection = null; + maxActiveTicks = 0; } private boolean isDashBlocked(EntityLivingBase caster) { @@ -226,66 +260,8 @@ public class AbilityDash extends Ability implements IAbilityDash { return !caster.worldObj.getCollidingBoundingBoxes(caster, caster.boundingBox.copy().offset(nextX, 0, nextZ)).isEmpty(); } - // ==================== PREVIEW MODE ==================== - - private transient double previewDirX, previewDirZ; - private transient double previewStartX, previewStartZ; - private transient boolean previewDashing = false; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewStartX = npc.posX; - previewStartZ = npc.posZ; - previewDashing = false; - - // Pick a random direction based on mode - DashDirection[] directions = dashMode == DashMode.AGGRESSIVE - ? AGGRESSIVE_DIRECTIONS - : DEFENSIVE_DIRECTIONS; - DashDirection dir = directions[RANDOM.nextInt(directions.length)]; - - float baseYaw; - if (previewTarget != null) { - double dx = previewTarget.posX - npc.posX; - double dz = previewTarget.posZ - npc.posZ; - baseYaw = (float) Math.toDegrees(Math.atan2(-dx, dz)); - } else { - baseYaw = npc.rotationYaw; - } - - float dashYaw = baseYaw + dir.getAngleOffset(); - float yawRad = (float) Math.toRadians(dashYaw); - previewDirX = -Math.sin(yawRad); - previewDirZ = Math.cos(yawRad); - previewDashing = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewDashing) return; - - double distTraveled = Math.sqrt( - Math.pow(npc.posX - previewStartX, 2) + - Math.pow(npc.posZ - previewStartZ, 2) - ); - - if (distTraveled >= dashDistance) { - previewDashing = false; - return; - } - - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewDirX * dashSpeed; - npc.posZ += previewDirZ * dashSpeed; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return (int) Math.ceil(dashDistance / dashSpeed) + 5; } @@ -309,7 +285,7 @@ public class AbilityDash extends Ability implements IAbilityDash { this.dashMode = DashMode.DEFENSIVE; } this.dashDistance = nbt.hasKey("dashDistance") ? nbt.getFloat("dashDistance") : 4.0f; - this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 1.5f; + this.dashSpeed = nbt.hasKey("dashSpeed") ? nbt.getFloat("dashSpeed") : 0.5f; } // Getters & Setters @@ -351,4 +327,17 @@ public class AbilityDash extends Ability implements IAbilityDash { public DashDirection getChosenDirection() { return chosenDirection; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.enumField("ability.dashMode", DashMode.class, this::getDashModeEnum, this::setDashModeEnum) + .hover("ability.hover.dashMode"), + FieldDef.row( + FieldDef.floatField("ability.dashDistance", this::getDashDistance, this::setDashDistance), + FieldDef.floatField("ability.dashSpeed", this::getDashSpeed, this::setDashSpeed) + ) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java index 36bc898b2..21d4073ed 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDisc.java @@ -12,41 +12,55 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityDisc; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityDisc; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityDisc; -import noppes.npcs.entity.EntityNPCInterface; + +import java.util.Arrays; +import java.util.List; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** * Disc ability: Spawns a flat spinning disc projectile. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. * Has optional boomerang behavior to return to owner. */ public class AbilityDisc extends Ability implements IAbilityDisc { - // Disc geometry + private static final int MAX_PROJECTILES = 8; + + // Disc geometry (shared) private float discRadius = 1.0f; private float discThickness = 0.2f; + private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) - // Boomerang properties + // Boomerang properties (shared) private boolean boomerang = false; private int boomerangDelay = 40; - // Energy data classes - private EnergyColorData colorData = new EnergyColorData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f); - private EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f); - private EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); - private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); + // Projectile count and fire stagger + private int projectileCount = 1; + private int fireDelay = 0; - // Transient state for disc entity (used during windup charging) - private transient EntityAbilityDisc discEntity = null; + // Shared visual data (all projectiles use these) + private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF8800, true, 0.4f, 0.5f, 5.0f); + private EnergyLightningData lightningData = new EnergyLightningData(); + private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + + // Shared combat/movement data + private final EnergyCombatData combatData = new EnergyCombatData(8.0f, 1.2f, 0.15f, false, 3.0f, 0.5f); + private final EnergyHomingData homingData = new EnergyHomingData(0.6f, true, 0.12f, 18.0f); + private final EnergyLifespanData lifespanData = new EnergyLifespanData(35.0f, 200); + + // Per-projectile data (anchor + optional color override) + private ProjectileData[] projectiles; + + // Transient entity state + private transient EntityAbilityDisc[] discEntities; public AbilityDisc() { this.typeId = "ability.cnpc.disc"; @@ -59,20 +73,90 @@ public class AbilityDisc extends Ability implements IAbilityDisc { this.lockMovement = LockMovementType.WINDUP; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animations this.windUpAnimationName = "Ability_Disc_Windup"; this.activeAnimationName = "Ability_Disc_Active"; + initProjectiles(1); + } + + private void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + /** + * Disc anchor order is REVERSED from Orb/Beam: [0]=LEFT_HAND, [1]=RIGHT_HAND + */ + private AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; + default: return AnchorPoint.FRONT; + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { + return projectileCount; + } + + public int getFireDelay() { + return fireDelay; + } + + public void setFireDelay(int delay) { + this.fireDelay = Math.max(0, delay); + } + + // Legacy compat + public int getDualFireDelay() { return fireDelay; } + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Disc"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityDisc disc = (AbilityDisc) a; + a.setName("Dual Disc"); + disc.setProjectileCount(2); + disc.setFireDelay(10); + // Set color override for second disc + disc.projectiles[1].colorOverride = true; + disc.projectiles[1].innerColor = 0xFFFFFF; + disc.projectiles[1].outerColor = 0x8800FF; + a.setWindUpAnimationName("Ability_DiscDual_Windup"); + a.setActiveAnimationName("Ability_DiscDual_Active"); + }) + ); } @Override - public boolean hasTypeSettings() { + public boolean allowOverlap() { return true; } @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityDisc(this, callback); + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); } @Override @@ -85,48 +169,115 @@ public class AbilityDisc extends Ability implements IAbilityDisc { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; + /** + * Create disc entities. + * NPC: target is the aggro target — discs will home toward it. + * Player: target is null — discs fire in caster's look direction. + */ + private EntityAbilityDisc[] createDiscEntities(EntityLivingBase caster, EntityLivingBase target, World world) { + EntityAbilityDisc[] entities = new EntityAbilityDisc[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + entities[i] = new EntityAbilityDisc( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + discRadius, discThickness, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData, + boomerang, boomerangDelay); + entities[i].setEffects(this.effects); + entities[i].setSourceAbility(this); } - - // Start moving the disc that was spawned during windup - if (discEntity != null && !discEntity.isDead) { - discEntity.startMoving(target); + if (projectileCount == 2 && entities[0] != null && entities[1] != null) { + entities[0].setSiblingEntityId(entities[1].getEntityId()); + entities[1].setSiblingEntityId(entities[0].getEntityId()); } + return entities; + } - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class + private void fireDiscEntity(EntityAbilityDisc disc, EntityLivingBase target) { + if (disc == null || disc.isDead) return; + if (isPreview()) { + disc.startPreviewFiring(); + } else { + disc.startMoving(target); + } } @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; - // Spawn disc in charging mode on first tick of windup if (tick == 1) { - // Create disc in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - discEntity = new EntityAbilityDisc( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - discRadius, discThickness, - colorData, combatData, homingData, lightningData, lifespanData, - boomerang, boomerangDelay); - discEntity.setupCharging(anchorData, windUpTicks); + discEntities = createDiscEntities(caster, target, world); + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + discEntities[i].setupPreview(caster, discRadius, discThickness, resolved, lightningData, projectiles[i].anchor, windUpTicks, vertical); + } else { + discEntities[i].setupCharging(projectiles[i].anchor, windUpTicks, vertical); + } + spawnAbilityEntity(world, discEntities[i]); + } + } + } - discEntity.setEffects(this.effects); - world.spawnEntityInWorld(discEntity); + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + discEntities = createDiscEntities(caster, target, world); + for (EntityAbilityDisc disc : discEntities) { + spawnAbilityEntity(world, disc); + } + for (EntityAbilityDisc disc : discEntities) { + fireDiscEntity(disc, target); + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + if (world.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (discEntities == null) return; + + // Fire first projectile immediately + fireDiscEntity(discEntities[0], target); + + // Fire remaining projectiles if no delay + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireDiscEntity(discEntities[i], target); + } } } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (discEntity == null || discEntity.isDead) { - discEntity = null; + if (discEntities == null) { + signalCompletion(); + return; + } + + // Fire staggered projectiles + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireDiscEntity(discEntities[i], target); + } + } + } + + // Check if all entities are dead + boolean allDead = true; + for (EntityAbilityDisc disc : discEntities) { + if (disc != null && !disc.isDead) { + allDead = false; + break; + } + } + if (allDead) { signalCompletion(); } } @@ -135,18 +286,29 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public void onComplete(EntityLivingBase caster, EntityLivingBase target) { } + @Override + public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { + cleanup(); + } + @Override public void cleanup() { - // Despawn disc entity if still alive - if (discEntity != null && !discEntity.isDead) { - discEntity.setDead(); + if (discEntities != null) { + for (int i = 0; i < discEntities.length; i++) { + if (discEntities[i] != null && !discEntities[i].isDead) { + discEntities[i].setDead(); + } + discEntities[i] = null; + } } - discEntity = null; + discEntities = null; } @Override public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { + // NPC: telegraph on aggro target position + // Player: no telegraph (discs fire in look direction, no fixed position to mark) + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { return null; } @@ -175,108 +337,336 @@ public class AbilityDisc extends Ability implements IAbilityDisc { public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("discRadius", discRadius); nbt.setFloat("discThickness", discThickness); + nbt.setBoolean("vertical", vertical); nbt.setBoolean("boomerang", boomerang); nbt.setInteger("boomerangDelay", boomerangDelay); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared visual data + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + + // Shared combat/movement data combatData.writeNBT(nbt); homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); lifespanData.writeNBT(nbt); + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } } @Override public void readTypeNBT(NBTTagCompound nbt) { this.discRadius = nbt.hasKey("discRadius") ? nbt.getFloat("discRadius") : 1.0f; this.discThickness = nbt.hasKey("discThickness") ? nbt.getFloat("discThickness") : 0.2f; + this.vertical = nbt.hasKey("vertical") && nbt.getBoolean("vertical"); this.boomerang = nbt.hasKey("boomerang") && nbt.getBoolean("boomerang"); this.boomerangDelay = nbt.hasKey("boomerangDelay") ? nbt.getInteger("boomerangDelay") : 40; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); + + int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + initProjectiles(count); + + // Read fireDelay with fallback to old dualFireDelay key + if (nbt.hasKey("fireDelay")) { + this.fireDelay = nbt.getInteger("fireDelay"); + } else if (nbt.hasKey("dualFireDelay")) { + this.fireDelay = nbt.getInteger("dualFireDelay"); + } else { + this.fireDelay = 0; + } + + // Shared combat/movement data combatData.readNBT(nbt); homingData.readNBT(nbt); - lightningData.readNBT(nbt); lifespanData.readNBT(nbt); + + // Determine format and read accordingly + if (nbt.hasKey("Projectile_0")) { + NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); + if (proj0.hasKey("colorOverride")) { + // NEW format: shared visuals at root + ProjectileData per projectile + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } else { + // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) + // Read primary visuals from Projectile_0 + displayData.readNBT(proj0); + lightningData.readNBT(proj0); + projectiles[0].anchor.readNBT(proj0); + + // Read remaining projectiles, set color override if colors differ + for (int i = 1; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); + projectiles[i].anchor.readNBT(projNbt); + + // Check if this projectile had different colors + EnergyDisplayData tempDisplay = new EnergyDisplayData(); + tempDisplay.readNBT(projNbt); + if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { + projectiles[i].colorOverride = true; + projectiles[i].innerColor = tempDisplay.innerColor; + projectiles[i].outerColor = tempDisplay.outerColor; + } + } + } + } + } else { + // LEGACY flat format: all data at root level + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + projectiles[0].anchor.readNBT(nbt); + } } - // Getters & Setters + // ═══════════════════════════════════════════════════════════════════ + // API GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ + public float getSpeed() { return homingData.speed; } public void setSpeed(float speed) { homingData.speed = speed; } + public float getDiscRadius() { return discRadius; } public void setDiscRadius(float discRadius) { this.discRadius = discRadius; } + public float getDiscThickness() { return discThickness; } public void setDiscThickness(float discThickness) { this.discThickness = discThickness; } - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { lifespanData.maxLifetime = maxLifetime; } - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { combatData.knockbackUp = knockbackUp; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { homingData.homingRange = homingRange; } + + public boolean isVertical() { return vertical; } + public void setVertical(boolean vertical) { this.vertical = vertical; } + public boolean isBoomerang() { return boomerang; } public void setBoomerang(boolean boomerang) { this.boomerang = boomerang; } + public int getBoomerangDelay() { return boomerangDelay; } public void setBoomerangDelay(int boomerangDelay) { this.boomerangDelay = boomerangDelay; } + + public float getMaxDistance() { return lifespanData.maxDistance; } + public void setMaxDistance(float d) { lifespanData.maxDistance = d; } + + public int getMaxLifetime() { return lifespanData.maxLifetime; } + public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } + + public float getDamage() { return combatData.damage; } + public void setDamage(float d) { combatData.damage = d; } + + public float getKnockback() { return combatData.knockback; } + public void setKnockback(float k) { combatData.knockback = k; } + + public float getKnockbackUp() { return combatData.knockbackUp; } + public void setKnockbackUp(float k) { combatData.knockbackUp = k; } + + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean h) { homingData.homing = h; } + + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float s) { homingData.homingStrength = s; } + + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float r) { homingData.homingRange = r; } + public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { combatData.explosive = explosive; } + public void setExplosive(boolean e) { combatData.explosive = e; } + public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { combatData.explosionRadius = explosionRadius; } + public void setExplosionRadius(float r) { combatData.explosionRadius = r; } + public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { combatData.explosionDamageFalloff = explosionDamageFalloff; } - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { colorData.outerColor = outerColor; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { colorData.outerColorAlpha = outerColorAlpha; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; } - public float getRotationSpeed() { return colorData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { colorData.rotationSpeed = rotationSpeed; } + public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } + + // Shared display data (primary colors) + public int getInnerColor() { return displayData.innerColor; } + public void setInnerColor(int c) { displayData.innerColor = c; } + + public int getOuterColor() { return displayData.outerColor; } + public void setOuterColor(int c) { displayData.outerColor = c; } + + public float getOuterColorWidth() { return displayData.outerColorWidth; } + public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } + + public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } + + public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } + + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } + + // Shared lightning data public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { lightningData.lightningEffect = lightningEffect; } + public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } + public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { lightningData.lightningDensity = lightningDensity; } + public void setLightningDensity(float d) { lightningData.lightningDensity = d; } + public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { lightningData.lightningRadius = lightningRadius; } - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } + public void setLightningRadius(float r) { lightningData.lightningRadius = r; } + + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } + + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } + + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } + + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } + + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } @Override - public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); } + public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } @Override - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; + } - EntityAbilityDisc disc = new EntityAbilityDisc(npc.worldObj); - disc.setupPreview(npc, discRadius, discThickness, colorData, lightningData, anchorData, windUpTicks); - return disc; + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; + } + + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } + + private int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); } @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } + + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + // Type tab - projectile count and fire delay + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) + )); + + // Type tab - disc properties + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + )); + defs.add(FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback)); + defs.add(FieldDef.section("ability.section.disc")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.radius", this::getDiscRadius, this::setDiscRadius), + FieldDef.floatField("gui.thickness", this::getDiscThickness, this::setDiscThickness) + )); + defs.add(FieldDef.boolField("ability.vertical", this::isVertical, this::setVertical) + .hover("ability.hover.vertical")); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming)); + defs.add(FieldDef.section("ability.section.boomerang")); + defs.add(FieldDef.boolField("gui.enabled", this::isBoomerang, this::setBoomerang).hover("ability.hover.boomerang")); + defs.add(FieldDef.intField("gui.delay", this::getBoomerangDelay, this::setBoomerangDelay).visibleWhen(this::isBoomerang)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); + + // Visual tab - shared primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Visual tab - shared effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + // Anchor point + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEnergyBeam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEnergyBeam.java deleted file mode 100644 index 700f771c7..000000000 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityEnergyBeam.java +++ /dev/null @@ -1,285 +0,0 @@ -package kamkeel.npcs.controllers.data.ability.type; - -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.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.*; -import kamkeel.npcs.controllers.data.telegraph.Telegraph; -import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import kamkeel.npcs.entity.EntityAbilityBeam; -import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityEnergyBeam; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.api.ability.type.IAbilityEnergyBeam; -import noppes.npcs.entity.EntityNPCInterface; - -/** - * Energy Beam ability: A homing head with a trailing path. - * The beam stays attached to the origin and curves as it homes in on target. - * Cannot cross over itself (self-intersection prevention). - */ -public class AbilityEnergyBeam extends Ability implements IAbilityEnergyBeam { - - // Shape properties (standalone) - private float beamWidth = 0.4f; - private float headSize = 0.6f; - - // Data classes - private EnergyColorData colorData = new EnergyColorData(0xFFFFFF, 0x00AAFF, true, 0.4f, 0.5f, 6.0f); - private EnergyCombatData combatData = new EnergyCombatData(10.0f, 1.5f, 0.2f, false, 4.0f, 0.5f); - private EnergyHomingData homingData = new EnergyHomingData(0.4f, true, 0.1f, 15.0f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyLifespanData lifespanData = new EnergyLifespanData(25.0f, 200); - private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); - - // Transient state for beam entity (used during windup charging) - private transient EntityAbilityBeam beamEntity = null; - - public AbilityEnergyBeam() { - this.typeId = "ability.cnpc.beam"; - this.name = "Beam"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 20.0f; - this.minRange = 5.0f; - this.cooldownTicks = 0; - this.windUpTicks = 40; - this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; - this.telegraphType = TelegraphType.CIRCLE; - this.showTelegraph = true; - // Default built-in animations - this.windUpAnimationName = "Ability_Beam_Windup"; - this.activeAnimationName = "Ability_Beam_Active"; - } - - @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityEnergyBeam(this, callback); - } - - @Override - public boolean isTargetingModeLocked() { - return true; - } - - @Override - public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; - } - - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; - } - - // Start firing the beam that was spawned during windup - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.startFiring(target); - } - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class - } - - @Override - public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; - - // Spawn beam in charging mode on first tick of windup - if (tick == 1) { - float offsetDist = 1.0f; - - // Create beam in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData, offsetDist); - beamEntity = new EntityAbilityBeam( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, - beamWidth, headSize, - colorData, combatData, homingData, lightningData, lifespanData, - lockMovement.locksActive()); - beamEntity.setupCharging(anchorData, windUpTicks, offsetDist); - - beamEntity.setEffects(this.effects); - world.spawnEntityInWorld(beamEntity); - } - } - - @Override - public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (beamEntity == null || beamEntity.isDead) { - beamEntity = null; - signalCompletion(); - } - } - - @Override - public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - } - - @Override - public void cleanup() { - // Despawn beam entity if still alive - if (beamEntity != null && !beamEntity.isDead) { - beamEntity.setDead(); - } - beamEntity = null; - } - - @Override - public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { - return null; - } - - // Create circle telegraph at target position - Telegraph telegraph = Telegraph.circle(headSize * 2.0f); - telegraph.setDurationTicks(windUpTicks); - telegraph.setColor(windUpColor); - telegraph.setWarningColor(activeColor); - telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); - telegraph.setHeightOffset(telegraphHeightOffset); - - // Position at target and follow target during windup - TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); - instance.setCasterEntityId(caster.getEntityId()); - instance.setEntityIdToFollow(target.getEntityId()); - - return instance; - } - - @Override - public float getTelegraphRadius() { - return headSize * 2.0f; - } - - @Override - public void writeTypeNBT(NBTTagCompound nbt) { - nbt.setFloat("beamWidth", beamWidth); - nbt.setFloat("headSize", headSize); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); - combatData.writeNBT(nbt); - homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); - lifespanData.writeNBT(nbt); - } - - @Override - public void readTypeNBT(NBTTagCompound nbt) { - this.beamWidth = nbt.hasKey("beamWidth") ? nbt.getFloat("beamWidth") : 0.4f; - this.headSize = nbt.hasKey("headSize") ? nbt.getFloat("headSize") : 0.6f; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); - combatData.readNBT(nbt); - homingData.readNBT(nbt); - lightningData.readNBT(nbt); - lifespanData.readNBT(nbt); - } - - // Getters & Setters - Standalone fields - public float getBeamWidth() { return beamWidth; } - public void setBeamWidth(float beamWidth) { this.beamWidth = beamWidth; } - public float getHeadSize() { return headSize; } - public void setHeadSize(float headSize) { this.headSize = headSize; } - - // Getters & Setters - Color data - public int getInnerColor() { return colorData.innerColor; } - public void setInnerColor(int innerColor) { this.colorData.innerColor = innerColor; } - public int getOuterColor() { return colorData.outerColor; } - public void setOuterColor(int outerColor) { this.colorData.outerColor = outerColor; } - public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } - public void setOuterColorEnabled(boolean outerColorEnabled) { this.colorData.outerColorEnabled = outerColorEnabled; } - public float getOuterColorWidth() { return colorData.outerColorWidth; } - public void setOuterColorWidth(float outerColorWidth) { this.colorData.outerColorWidth = outerColorWidth; } - public float getOuterColorAlpha() { return colorData.outerColorAlpha; } - public void setOuterColorAlpha(float outerColorAlpha) { this.colorData.outerColorAlpha = outerColorAlpha; } - public float getRotationSpeed() { return colorData.rotationSpeed; } - public void setRotationSpeed(float rotationSpeed) { this.colorData.rotationSpeed = rotationSpeed; } - - // Getters & Setters - Combat data - public float getDamage() { return combatData.damage; } - public void setDamage(float damage) { this.combatData.damage = damage; } - public float getKnockback() { return combatData.knockback; } - public void setKnockback(float knockback) { this.combatData.knockback = knockback; } - public float getKnockbackUp() { return combatData.knockbackUp; } - public void setKnockbackUp(float knockbackUp) { this.combatData.knockbackUp = knockbackUp; } - public boolean isExplosive() { return combatData.explosive; } - public void setExplosive(boolean explosive) { this.combatData.explosive = explosive; } - public float getExplosionRadius() { return combatData.explosionRadius; } - public void setExplosionRadius(float explosionRadius) { this.combatData.explosionRadius = explosionRadius; } - public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } - public void setExplosionDamageFalloff(float explosionDamageFalloff) { this.combatData.explosionDamageFalloff = explosionDamageFalloff; } - - // Getters & Setters - Homing data - public float getSpeed() { return homingData.speed; } - public void setSpeed(float speed) { this.homingData.speed = speed; } - public boolean isHoming() { return homingData.homing; } - public void setHoming(boolean homing) { this.homingData.homing = homing; } - public float getHomingStrength() { return homingData.homingStrength; } - public void setHomingStrength(float homingStrength) { this.homingData.homingStrength = homingStrength; } - public float getHomingRange() { return homingData.homingRange; } - public void setHomingRange(float homingRange) { this.homingData.homingRange = homingRange; } - - // Getters & Setters - Lightning data - public boolean hasLightningEffect() { return lightningData.lightningEffect; } - public void setLightningEffect(boolean lightningEffect) { this.lightningData.lightningEffect = lightningEffect; } - public float getLightningDensity() { return lightningData.lightningDensity; } - public void setLightningDensity(float lightningDensity) { this.lightningData.lightningDensity = lightningDensity; } - public float getLightningRadius() { return lightningData.lightningRadius; } - public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; } - - // Getters & Setters - Lifespan data - public float getMaxDistance() { return lifespanData.maxDistance; } - public void setMaxDistance(float maxDistance) { this.lifespanData.maxDistance = maxDistance; } - public int getMaxLifetime() { return lifespanData.maxLifetime; } - public void setMaxLifetime(int maxLifetime) { this.lifespanData.maxLifetime = maxLifetime; } - - // Getters & Setters - Anchor point - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - - @Override - public int getAnchorPoint() { return anchorData.anchorPoint.ordinal(); } - - @Override - public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityBeam beam = new EntityAbilityBeam(npc.worldObj); - beam.setupPreview(npc, beamWidth, headSize, colorData, lightningData, anchorData, windUpTicks, 1.0f); - return beam; - } - - @Override - public int getPreviewActiveDuration() { - return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; - } -} diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java index 223a1180c..477be2cc4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityGuard.java @@ -1,24 +1,29 @@ package kamkeel.npcs.controllers.data.ability.type; -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.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.UserType; +import kamkeel.npcs.controllers.data.ability.*; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityGuard; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.api.handler.data.IAnimation; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.controllers.data.PlayerData; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilityGuard; -import java.util.Random; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import noppes.npcs.util.ValueUtil; + +import java.util.Arrays; +import java.util.List; /** * Guard ability: Defensive stance that reduces incoming damage. @@ -26,54 +31,62 @@ import java.util.Random; */ public class AbilityGuard extends Ability implements IAbilityGuard { - private static final Random RANDOM = new Random(); - - // Type-specific parameters private int durationTicks = 60; private float damageReduction = 0.5f; - private boolean canCounter = false; - private CounterType counterType = CounterType.FLAT; + private AbilityGuard.CounterType counterType = AbilityGuard.CounterType.FLAT; private float counterValue = 6.0f; - private float counterChance = 0.3f; - private String counterSound = "random.wood_click"; + private String counterSound = "random.anvil_land"; + private boolean canCounter = false; + private int counterWindow = 10; private int counterAnimationId = -1; + private String counterAnimationName; // Runtime state private transient EntityLivingBase lastAttacker; private transient boolean counterTriggered; + private transient boolean counterEligible; private transient float lastDamageTaken; - public enum CounterType { - FLAT, - PERCENT - } - public AbilityGuard() { this.typeId = "ability.cnpc.guard"; this.name = "Guard"; this.targetingMode = TargetingMode.SELF; this.lockMovement = LockMovementType.ACTIVE; this.cooldownTicks = 0; - this.windUpTicks = 10; + this.windUpTicks = 0; this.interruptible = false; // Hard to interrupt while guarding // No telegraph for guard - it's a defensive stance this.telegraphType = TelegraphType.NONE; this.showTelegraph = false; - this.windUpSound = "random.anvil_use"; - this.activeSound = "random.anvil_land"; - this.allowedBy = UserType.NPC_ONLY; + this.activeSound = "random.anvil_use"; + this.allowedBy = UserType.BOTH; + + this.activeAnimationName = "Ability_Guard_Active"; + this.counterAnimationName = "Ability_Guard_Counter"; } @Override - public boolean hasTypeSettings() { - return true; + public boolean hasDamage() { + return false; } @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui( - IAbilityConfigCallback callback) { - return new SubGuiAbilityGuard(this, callback); + public boolean allowBurst() { + return false; + } + + public enum CounterType { + FLAT, + PERCENT; + + @Override + public String toString() { + switch (this) { + case FLAT: return "ability.counter.flat"; + case PERCENT: return "ability.counter.percent"; + default: return name(); + } + } } @Override @@ -91,41 +104,56 @@ public class AbilityGuard extends Ability implements IAbilityGuard { lastAttacker = null; counterTriggered = false; lastDamageTaken = 0.0f; + counterEligible = true; } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Counter attack logic if triggered - if (canCounter && counterTriggered && lastAttacker != null && !world.isRemote) { + if (canCounter && counterEligible && counterTriggered && lastAttacker != null && !world.isRemote) { performCounter(caster, world); } - // Check if guard duration has ended + if (tick > counterWindow && counterEligible) { + counterEligible = false; + } + if (tick >= durationTicks) { signalCompletion(); } + + // Just enough to see the counter animation + if (counterTriggered && tick >= counterWindow + 10) { + signalCompletion(); + } } - /** - * Called externally when the caster takes damage while guarding. - * This should be called from the damage handling code. - * - * @param attacker The entity that attacked - * @param damage The damage amount (after reduction) - */ public void onDamageTaken(EntityLivingBase caster, EntityLivingBase attacker, DamageSource source, float damage) { - if (!canCounter || attacker == null) return; - if (!isDirectHit(source)) return; - if (RANDOM.nextFloat() >= counterChance) return; + if (!isGuarding() || attacker == null) return; lastAttacker = attacker; lastDamageTaken = damage; - counterTriggered = true; - // Counter will be performed in onActiveTick - don't self-interrupt + + float reduction = ValueUtil.clamp(getDamageReductionFactor(), 0, damage); + float newHealth = ValueUtil.clamp(caster.getHealth() + reduction, 0, caster.getMaxHealth()); + + caster.setHealth(newHealth); + + if (!canCounter || !counterEligible || counterTriggered || !isDirectHit(source)) { + caster.setHealth(newHealth); + } else { + caster.setHealth(ValueUtil.clamp(caster.getHealth() + damage, 0, caster.getMaxHealth())); + counterTriggered = true; + } + } + + private boolean isDirectHit(DamageSource source) { + if (source == null) return false; + if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) return false; + return source.getEntity() instanceof EntityLivingBase; } private void performCounter(EntityLivingBase caster, World world) { - float counterDamage = counterType == CounterType.PERCENT + float counterDamage = counterType == AbilityGuard.CounterType.PERCENT ? lastDamageTaken * (counterValue / 100.0f) : counterValue; @@ -135,18 +163,32 @@ public class AbilityGuard extends Ability implements IAbilityGuard { } // Use shared animation utility - only available for NPCs if (caster instanceof EntityNPCInterface) { - ((EntityNPCInterface) caster).abilities.playAbilityAnimation(counterAnimationId); + if (getCounterAnimation() instanceof IAnimation) { + ((EntityNPCInterface) caster).abilities.playAbilityAnimation((Animation) getCounterAnimation()); + } + } else if (caster instanceof EntityPlayer) { + if (getCounterAnimation() instanceof IAnimation) { + PlayerData.get((EntityPlayer) caster).abilityData.playAbilityAnimation((Animation) getCounterAnimation()); + } } - counterTriggered = false; + counterEligible = false; lastAttacker = null; lastDamageTaken = 0.0f; } - private boolean isDirectHit(DamageSource source) { - if (source == null) return false; - if (source.isMagicDamage() || source.isFireDamage() || source.isExplosion()) return false; - return source.getEntity() instanceof EntityLivingBase; + private IAnimation getCounterAnimation() { + if (AnimationController.Instance == null) return null; + + if (counterAnimationId > 0) { + return AnimationController.Instance.get(counterAnimationId); + } + + if (!counterAnimationName.isEmpty()) { + return AnimationController.Instance.get(counterAnimationName, true); + } + + return null; } /** @@ -154,7 +196,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard { * Returns 0.5 for 50% reduction. */ public float getDamageReductionFactor() { - if (isExecuting() && getPhase() == kamkeel.npcs.controllers.data.ability.AbilityPhase.ACTIVE) { + if (isExecuting() && getPhase() == AbilityPhase.ACTIVE) { return damageReduction; } return 0.0f; @@ -164,7 +206,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard { * Check if the caster is currently in guard stance. */ public boolean isGuarding() { - return isExecuting() && getPhase() == kamkeel.npcs.controllers.data.ability.AbilityPhase.ACTIVE; + return isExecuting() && getPhase() == AbilityPhase.ACTIVE; } @Override @@ -185,11 +227,12 @@ public class AbilityGuard extends Ability implements IAbilityGuard { nbt.setInteger("durationTicks", durationTicks); nbt.setFloat("damageReduction", damageReduction); nbt.setBoolean("canCounter", canCounter); + nbt.setInteger("counterWindow", counterWindow); nbt.setString("counterType", counterType.name()); nbt.setFloat("counterValue", counterValue); - nbt.setFloat("counterChance", counterChance); nbt.setString("counterSound", counterSound); nbt.setInteger("counterAnimationId", counterAnimationId); + nbt.setString("counterAnimationName", counterAnimationName); } @Override @@ -197,6 +240,7 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.durationTicks = nbt.hasKey("durationTicks") ? nbt.getInteger("durationTicks") : 60; this.damageReduction = nbt.hasKey("damageReduction") ? nbt.getFloat("damageReduction") : 0.5f; this.canCounter = nbt.hasKey("canCounter") && nbt.getBoolean("canCounter"); + this.counterWindow = nbt.hasKey("counterWindow") ? nbt.getInteger("counterWindow") : 10; try { this.counterType = CounterType.valueOf(nbt.getString("counterType")); } catch (Exception e) { @@ -209,9 +253,11 @@ public class AbilityGuard extends Ability implements IAbilityGuard { } else { this.counterValue = 6.0f; } - this.counterChance = nbt.hasKey("counterChance") ? nbt.getFloat("counterChance") : 0.3f; this.counterSound = nbt.hasKey("counterSound") ? nbt.getString("counterSound") : "random.wood_click"; this.counterAnimationId = nbt.hasKey("counterAnimationId") ? nbt.getInteger("counterAnimationId") : -1; + this.counterAnimationName = nbt.hasKey("counterAnimationName") ? + nbt.getString("counterAnimationName") : + "Ability_Guard_Counter"; } // Getters & Setters @@ -223,17 +269,26 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.durationTicks = Math.max(1, durationTicks); } + @Override + public int getCounterWindow() { + return this.counterWindow; + } + + @Override + public void setCounterWindow(int ticks) { + this.counterWindow = Math.min(durationTicks, ticks); + } + + @Override public float getDamageReduction() { return damageReduction; } + @Override public void setDamageReduction(float damageReduction) { this.damageReduction = damageReduction; } - public boolean isCanCounter() { - return canCounter; - } @Override public boolean canCounter() { @@ -271,14 +326,6 @@ public class AbilityGuard extends Ability implements IAbilityGuard { this.counterValue = counterValue; } - public float getCounterChance() { - return counterChance; - } - - public void setCounterChance(float counterChance) { - this.counterChance = counterChance; - } - public String getCounterSound() { return counterSound; } @@ -294,4 +341,48 @@ public class AbilityGuard extends Ability implements IAbilityGuard { public void setCounterAnimationId(int counterAnimationId) { this.counterAnimationId = counterAnimationId; } + + public String getCounterAnimationName() { + return counterAnimationName; + } + + public void setCounterAnimationName(String name) { + this.counterAnimationName = name; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 1000), + FieldDef.floatField("ability.damageReduction", this::getDamageReduction, this::setDamageReduction), + FieldDef.section("ability.section.counter"), + FieldDef.boolField("gui.enabled", this::canCounter, this::setCanCounter).hover("ability.hover.canCounter"), + FieldDef.enumField("gui.type", CounterType.class, this::getCounterTypeEnum, this::setCounterTypeEnum) + .hover("ability.hover.counterType").visibleWhen(this::canCounter), + FieldDef.row( + FieldDef.floatField("gui.value", this::getCounterValue, this::setCounterValue) + .visibleWhen(this::canCounter), + FieldDef.intField("ability.counterWindow", this::getCounterWindow, this::setCounterWindow) + .visibleWhen(this::canCounter) + ), + FieldDef.stringField("gui.sound", this::getCounterSound, this::setCounterSound) + .visibleWhen(this::canCounter), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + + )); + + FieldDef.insertAfter(defs, "ability.activeSound", + FieldDef.soundSubGui("ability.counterSound", this::getCounterSound, this::setCounterSound) + .tab("Effects").visibleWhen(this::canCounter)); + + FieldDef.insertAfter(defs, "ability.activeAnimation", + FieldDef.animSubGui("ability.counterAnimation", + this::getCounterAnimationId, this::setCounterAnimationId, + this::getCounterAnimationName, this::setCounterAnimationName) + .tab("Effects").visibleWhen(this::canCounter)); + + FieldDef.modifyVisibility(defs, "ability.windUpAnimation", () -> false); + FieldDef.modifyVisibility(defs, "ability.windUpSound", () -> false); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java index 0700b1f01..58c2560a4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHazard.java @@ -1,10 +1,9 @@ package kamkeel.npcs.controllers.data.ability.type; -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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; @@ -14,13 +13,17 @@ import net.minecraft.potion.PotionEffect; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityHazard; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilityHazard; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -35,14 +38,35 @@ public class AbilityHazard extends Ability implements IAbilityHazard { public enum HazardShape { CIRCLE, RING, - CONE + CONE; + + @Override + public String toString() { + switch (this) { + case CIRCLE: return "ability.shape.circle"; + case RING: return "ability.shape.ring"; + case CONE: return "ability.shape.cone"; + default: return name(); + } + } } public enum PlacementMode { AT_CASTER, AT_TARGET, FOLLOW_CASTER, - FOLLOW_TARGET + FOLLOW_TARGET; + + @Override + public String toString() { + switch (this) { + case AT_CASTER: return "ability.placement.atCaster"; + case AT_TARGET: return "ability.placement.atTarget"; + case FOLLOW_CASTER: return "ability.placement.followCaster"; + case FOLLOW_TARGET: return "ability.placement.followTarget"; + default: return name(); + } + } } private int durationTicks = 100; @@ -88,18 +112,12 @@ public class AbilityHazard extends Ability implements IAbilityHazard { this.cooldownTicks = 0; this.windUpTicks = 30; this.telegraphType = TelegraphType.CIRCLE; + this.allowedBy = UserType.NPC_ONLY; } @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui( - IAbilityConfigCallback callback) { - return new SubGuiAbilityHazard(this, callback); + public boolean allowBurst() { + return false; } @Override @@ -186,14 +204,12 @@ public class AbilityHazard extends Ability implements IAbilityHazard { } break; case AT_TARGET: - // Use telegraph position if available, apply offset if (telegraph != null) { double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), minOffset, maxOffset, randomOffset, RANDOM); zoneX = pos[0]; zoneY = pos[1]; zoneZ = pos[2]; - // Update telegraph to show actual hazard position telegraph.setX(zoneX); telegraph.setY(zoneY); telegraph.setZ(zoneZ); @@ -232,7 +248,7 @@ public class AbilityHazard extends Ability implements IAbilityHazard { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; // Check if hazard duration has ended if (tick >= durationTicks) { @@ -240,53 +256,55 @@ public class AbilityHazard extends Ability implements IAbilityHazard { return; } - damagedThisTick.clear(); - ticksSinceDamage++; + if (!isPreview()) { + damagedThisTick.clear(); + ticksSinceDamage++; - switch (placement) { - case FOLLOW_CASTER: - zoneX = caster.posX; - zoneY = caster.posY; - zoneZ = caster.posZ; - break; - case FOLLOW_TARGET: - if (target != null) { - zoneX = target.posX; - zoneY = target.posY; - zoneZ = target.posZ; - } - break; - default: - break; - } - - if (ticksSinceDamage >= damageInterval) { - ticksSinceDamage = 0; - - AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( - zoneX - radius, zoneY - heightBelow, zoneZ - radius, - zoneX + radius, zoneY + heightAbove, zoneZ + radius - ); - - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); - - for (EntityLivingBase entity : entities) { - if (entity == caster && !affectsCaster) continue; - if (damagedThisTick.contains(entity.getEntityId())) continue; - if (!isInZone(entity, caster)) continue; - - if (damagePerSecond > 0) { - if (ignoreInvulnFrames) { - entity.hurtResistantTime = 0; + switch (placement) { + case FOLLOW_CASTER: + zoneX = caster.posX; + zoneY = caster.posY; + zoneZ = caster.posZ; + break; + case FOLLOW_TARGET: + if (target != null) { + zoneX = target.posX; + zoneY = target.posY; + zoneZ = target.posZ; } - // Apply damage with scripted event support (no knockback for hazard) - boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0); - if (!wasHit) continue; // Skip debuffs if hit was cancelled - } + break; + default: + break; + } - applyDebuffs(entity); - damagedThisTick.add(entity.getEntityId()); + if (ticksSinceDamage >= damageInterval) { + ticksSinceDamage = 0; + + AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( + zoneX - radius, zoneY - heightBelow, zoneZ - radius, + zoneX + radius, zoneY + heightAbove, zoneZ + radius + ); + + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, searchBox); + + for (EntityLivingBase entity : entities) { + if (entity == caster && !affectsCaster) continue; + if (damagedThisTick.contains(entity.getEntityId())) continue; + if (!isInZone(entity, caster)) continue; + + if (damagePerSecond > 0) { + if (ignoreInvulnFrames) { + entity.hurtResistantTime = 0; + } + // Apply damage with scripted event support (no knockback for hazard) + boolean wasHit = applyAbilityDamage(caster, entity, damagePerSecond, 0); + if (!wasHit) continue; // Skip debuffs if hit was cancelled + } + + applyDebuffs(entity); + damagedThisTick.add(entity.getEntityId()); + } } } } @@ -616,4 +634,35 @@ public class AbilityHazard extends Ability implements IAbilityHazard { public double getZoneZ() { return zoneZ; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks).range(1, 2000), + FieldDef.enumField("ability.shape", HazardShape.class, this::getShapeEnum, this::setShapeEnum) + .hover("ability.hover.shape"), + FieldDef.enumField("ability.placement", PlacementMode.class, this::getPlacementEnum, this::setPlacementEnum) + .hover("ability.hover.placement"), + FieldDef.section("ability.section.area"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getRadius, this::setRadius), + FieldDef.floatField("ability.innerRadius", this::getInnerRadius, this::setInnerRadius) + ), + FieldDef.section("ability.section.damage"), + FieldDef.row( + FieldDef.floatField("ability.damagePerSecond", this::getDamagePerSecond, this::setDamagePerSecond), + FieldDef.intField("ability.damageInterval", this::getDamageInterval, this::setDamageInterval) + ), + FieldDef.section("ability.section.debuffs"), + FieldDef.row( + FieldDef.intField("ability.slownessLevel", this::getSlownessLevel, this::setSlownessLevel), + FieldDef.intField("ability.debuffDuration", this::getDebuffDuration, this::setDebuffDuration) + ), + FieldDef.intField("ability.poisonLevel", this::getPoisonLevel, this::setPoisonLevel), + FieldDef.boolField("ability.affectsCaster", this::isAffectsCaster, this::setAffectsCaster) + .hover("ability.hover.affectsCaster"), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java index 898d54f57..d913fe586 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeal.java @@ -1,7 +1,5 @@ package kamkeel.npcs.controllers.data.ability.type; -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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; @@ -11,14 +9,16 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityHeal; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.client.gui.builder.FieldDef; import noppes.npcs.api.ability.type.IAbilityHeal; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -59,14 +59,13 @@ public class AbilityHeal extends Ability implements IAbilityHeal { } @Override - public boolean hasTypeSettings() { - return true; + public boolean hasDamage() { + return false; } @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityHeal(this, callback); + public boolean allowBurst() { + return false; } @Override @@ -81,27 +80,31 @@ public class AbilityHeal extends Ability implements IAbilityHeal { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; - getHealedAllies().clear(); + if (!isPreview()) { + getHealedAllies().clear(); - // Always find allies if we're healing them (needed for both instant and HoT) - if (healAllies && healRadius > 0) { - findAlliesInRadius(caster, world); + // Always find allies if we're healing them (needed for both instant and HoT) + if (healAllies && healRadius > 0) { + findAlliesInRadius(caster, world); + } + + if (instantHeal) { + // Instant heal - apply all healing now + if (healSelf) { + healEntity(caster); + spawnHealParticles(world, caster); + } + + for (EntityLivingBase ally : getHealedAllies()) { + healEntity(ally); + spawnHealParticles(world, ally); + } + } } if (instantHeal) { - // Instant heal - apply all healing now - if (healSelf) { - healEntity(caster); - spawnHealParticles(world, caster); - } - - for (EntityLivingBase ally : getHealedAllies()) { - healEntity(ally); - spawnHealParticles(world, ally); - } - // Instant heal completes immediately signalCompletion(); } @@ -110,7 +113,7 @@ public class AbilityHeal extends Ability implements IAbilityHeal { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote || instantHeal) return; + if ((world.isRemote && !isPreview()) || instantHeal) return; // Heal over time - distribute heal across duration ticks if (tick % 10 == 0) { @@ -289,4 +292,27 @@ public class AbilityHeal extends Ability implements IAbilityHeal { public void setInstantHeal(boolean instantHeal) { this.instantHeal = instantHeal; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.boolField("ability.instantHeal", this::isInstantHeal, this::setInstantHeal) + .hover("ability.hover.instant"), + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) + .range(1, 1000).visibleWhen(() -> !this.isInstantHeal()), + FieldDef.section("ability.section.healing"), + FieldDef.row( + FieldDef.floatField("ability.healAmount", this::getHealAmount, this::setHealAmount), + FieldDef.floatField("ability.healPercent", this::getHealPercent, this::setHealPercent) + ), + FieldDef.floatField("ability.healRadius", this::getHealRadius, this::setHealRadius), + FieldDef.row( + FieldDef.boolField("ability.healSelf", this::isHealSelf, this::setHealSelf) + .hover("ability.hover.healSelf"), + FieldDef.boolField("ability.healAllies", this::isHealAllies, this::setHealAllies) + .hover("ability.hover.healAllies") + ) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java index 7d0c217c0..dd5d5fc09 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java @@ -6,49 +6,44 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityHeavyHit; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityHeavyHit; -import noppes.npcs.entity.EntityNPCInterface; + +import java.util.Arrays; +import java.util.List; /** - * Heavy Hit ability: Single-target melee attack with optional stun. - * Deals high damage to one target and can stun them. + * Heavy Hit ability: AOE rectangle melee attack in front of the caster. + * Deals high damage to all entities within a rectangular zone and can apply effects. + * Has a LINE telegraph showing the hit area during windup, making it dodgeable. */ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { private float damage = 8.0f; private float knockback = 2.0f; + private float hitLength = 4.0f; // How far in front of the caster the hit reaches + private float hitWidth = 3.0f; // How wide to each side (total width = hitWidth * 2) public AbilityHeavyHit() { this.typeId = "ability.cnpc.heavy_hit"; this.name = "Heavy Hit"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 3.0f; + this.targetingMode = TargetingMode.AOE_SELF; + this.maxRange = 5.0f; this.minRange = 0.0f; - this.lockMovement = LockMovementType.NO; + this.lockMovement = LockMovementType.WINDUP; this.cooldownTicks = 0; this.windUpTicks = 30; - this.telegraphType = TelegraphType.POINT; - this.showTelegraph = false; + this.telegraphType = TelegraphType.LINE; + this.showTelegraph = true; this.windUpSound = "random.anvil_use"; this.activeSound = "random.anvil_land"; - } - - @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui( - IAbilityConfigCallback callback) { - return new SubGuiAbilityHeavyHit(this, callback); + this.windUpAnimationName = "Ability_HeavyHit_Windup"; + this.activeAnimationName = "Ability_HeavyHit_Active"; } @Override @@ -58,43 +53,92 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { @Override public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + return new TargetingMode[]{TargetingMode.AOE_SELF}; + } + + @Override + public float getTelegraphLength() { + return hitLength; + } + + @Override + public float getTelegraphWidth() { + return hitWidth * 2.0f; // Total width (hitWidth is distance to each side) } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote || target == null) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - // Apply damage with scripted event support - boolean wasHit = applyAbilityDamage(caster, target, damage, knockback); + if (!isPreview()) { + // Calculate forward and right vectors from caster yaw + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double forwardX = -Math.sin(yawRad); + double forwardZ = Math.cos(yawRad); + double rightX = forwardZ; // perpendicular right + double rightZ = -forwardX; - // Apply effects if hit wasn't cancelled - if (wasHit) { - applyEffects(target); + // Search area: AABB that encompasses the rectangle + float searchDist = Math.max(hitLength, hitWidth) + 1.0f; + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity( + caster, caster.boundingBox.expand(searchDist, 2, searchDist)); + + boolean anyHit = false; + for (Entity entity : entities) { + if (!(entity instanceof EntityLivingBase) || entity == caster) continue; + EntityLivingBase livingTarget = (EntityLivingBase) entity; + + double dx = livingTarget.posX - caster.posX; + double dz = livingTarget.posZ - caster.posZ; + + // Project onto forward direction (must be in front, within hitLength) + double forwardDist = dx * forwardX + dz * forwardZ; + if (forwardDist < 0 || forwardDist > hitLength) continue; + + // Project onto right direction (must be within hitWidth to each side) + double sideDist = dx * rightX + dz * rightZ; + if (Math.abs(sideDist) > hitWidth) continue; + + // Entity is within the rectangle - apply damage + boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); + if (wasHit) { + applyEffects(livingTarget); + anyHit = true; + } + } + + // Play hit sound even if nothing was hit (the attack still happens) + if (!anyHit) { + world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); + } } - - // Heavy Hit is instant - signalCompletion(); } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Heavy Hit is instant, no active tick needed + // Just enough delay to see the active animation + if (tick == 10) + signalCompletion(); } @Override public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("damage", damage); nbt.setFloat("knockback", knockback); + nbt.setFloat("hitLength", hitLength); + nbt.setFloat("hitWidth", hitWidth); } @Override public void readTypeNBT(NBTTagCompound nbt) { this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 2.0f; + this.hitLength = nbt.hasKey("hitLength") ? nbt.getFloat("hitLength") : 4.0f; + this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 3.0f; } // Getters & Setters @@ -113,4 +157,37 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { public void setKnockback(float knockback) { this.knockback = knockback; } + + public float getHitLength() { + return hitLength; + } + + public void setHitLength(float hitLength) { + this.hitLength = hitLength; + } + + public float getHitWidth() { + return hitWidth; + } + + public void setHitWidth(float hitWidth) { + this.hitWidth = hitWidth; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + ), + FieldDef.section("ability.section.hitZone"), + FieldDef.row( + FieldDef.floatField("ability.hitLength", this::getHitLength, this::setHitLength), + FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth) + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java index acf5f0aa4..afffa9c13 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityLaserShot.java @@ -3,24 +3,25 @@ package kamkeel.npcs.controllers.data.ability.type; 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.AnchorPoint; import kamkeel.npcs.controllers.data.ability.LockMovementType; +import kamkeel.npcs.controllers.data.ability.RotationMode; import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.EnergyColorData; -import kamkeel.npcs.controllers.data.ability.data.EnergyCombatData; -import kamkeel.npcs.controllers.data.ability.data.EnergyLifespanData; -import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; +import kamkeel.npcs.controllers.data.ability.data.*; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityLaser; -import net.minecraft.entity.Entity; +import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; +import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityLaserShot; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.api.ability.type.IAbilityLaserShot; -import noppes.npcs.entity.EntityNPCInterface; + +import java.util.Arrays; +import java.util.List; /** * Laser Shot ability: Fast expanding thin line that pierces through targets. @@ -34,10 +35,12 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { private int lingerTicks = 8; // Data classes - private EnergyColorData colorData = new EnergyColorData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); - private EnergyCombatData combatData = new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f); - private EnergyLightningData lightningData = new EnergyLightningData(); - private EnergyLifespanData lifespanData = new EnergyLifespanData(40.0f, 100); + private final EnergyDisplayData colorData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); + private final EnergyCombatData combatData = new EnergyCombatData(6.0f, 0.5f, 0.05f, false, 2.0f, 0.5f); + private final EnergyLightningData lightningData = new EnergyLightningData(); + private final EnergyLifespanData lifespanData = new EnergyLifespanData(40.0f, 100); + private final EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); + private final EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); // Transient state for laser entity (used for movement locking) private transient EntityAbilityLaser laserEntity = null; @@ -50,7 +53,9 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { this.minRange = 3.0f; this.cooldownTicks = 0; this.windUpTicks = 15; - this.lockMovement = LockMovementType.WINDUP; + this.lockMovement = LockMovementType.WINDUP_AND_ACTIVE; + this.rotationMode = RotationMode.TRACK; + this.rotationPhase = LockMovementType.WINDUP; this.telegraphType = TelegraphType.LINE; this.showTelegraph = true; // Default built-in animations @@ -59,16 +64,10 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { } @Override - public boolean hasTypeSettings() { + public boolean allowOverlap() { return true; } - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityLaserShot(this, callback); - } - @Override public boolean isTargetingModeLocked() { return false; @@ -89,30 +88,65 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { return laserWidth * 2.0f; // Make telegraph slightly wider for visibility } + /** + * Spawn laser entity. + * NPC: target is the aggro target — laser expands toward it. + * Player: target is null — laser expands in caster's look direction. + */ + private EntityAbilityLaser spawnLaserEntity(EntityLivingBase caster, EntityLivingBase target, World world) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); + EntityAbilityLaser entity = new EntityAbilityLaser( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, + laserWidth, + colorData, combatData, lightningData, lifespanData, trajectoryData, + expansionSpeed, lingerTicks + ); + entity.setEffects(this.effects); + entity.setSourceAbility(this); + spawnAbilityEntity(world, entity); + return entity; + } + + private void fireLaserEntity(EntityAbilityLaser laser, EntityLivingBase target) { + if (laser == null || laser.isDead) return; + laser.setLockVerticalDirection(true); + laser.startMoving(target); + } + + @Override + public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + if (world.isRemote && !isPreview()) return; + + if (tick == 1) { + laserEntity = spawnLaserEntity(caster, target, world); + if (isPreview()) { + laserEntity.setupPreview(caster, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); + } else { + laserEntity.setupCharging(anchorData, windUpTicks); + } + } + } + + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + laserEntity = spawnLaserEntity(caster, target, world); + fireLaserEntity(laserEntity, target); + } + @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - double spawnX = caster.posX; - double spawnY = caster.posY + caster.getEyeHeight(); - double spawnZ = caster.posZ; + if (laserEntity == null) { + signalCompletion(); + return; + } - laserEntity = new EntityAbilityLaser( - world, caster, target, - spawnX, spawnY, spawnZ, - laserWidth, - colorData, combatData, lightningData, lifespanData, - expansionSpeed, lingerTicks - ); - - laserEntity.setEffects(this.effects); - world.spawnEntityInWorld(laserEntity); - - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class + fireLaserEntity(laserEntity, target); } @Override @@ -130,6 +164,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { + cleanup(); } @Override @@ -146,6 +181,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { nbt.setFloat("laserWidth", laserWidth); nbt.setFloat("expansionSpeed", expansionSpeed); nbt.setInteger("lingerTicks", lingerTicks); + anchorData.writeNBT(nbt); colorData.writeNBT(nbt); combatData.writeNBT(nbt); lightningData.writeNBT(nbt); @@ -157,6 +193,7 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { this.laserWidth = nbt.hasKey("laserWidth") ? nbt.getFloat("laserWidth") : 0.3f; this.expansionSpeed = nbt.hasKey("expansionSpeed") ? nbt.getFloat("expansionSpeed") : 3.0f; this.lingerTicks = nbt.hasKey("lingerTicks") ? nbt.getInteger("lingerTicks") : 8; + anchorData.readNBT(nbt); colorData.readNBT(nbt); combatData.readNBT(nbt); lightningData.readNBT(nbt); @@ -210,23 +247,78 @@ public class AbilityLaserShot extends Ability implements IAbilityLaserShot { public float getLightningRadius() { return lightningData.lightningRadius; } public void setLightningRadius(float lightningRadius) { this.lightningData.lightningRadius = lightningRadius; } - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; + public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - EntityAbilityLaser laser = new EntityAbilityLaser(npc.worldObj); - laser.setupPreview(npc, laserWidth, colorData, lightningData, expansionSpeed, lifespanData.maxDistance); - return laser; + public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } + public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } + public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } + public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } + public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } + public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } + public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } + public int getAnchorPoint() { + return anchorData.anchorPoint.ordinal(); } + public void setAnchorPoint(int point) { this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); } @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 60) : 60; } + @SideOnly(Side.CLIENT) @Override - public boolean spawnPreviewDuringWindup() { - return false; // Laser has no charging, spawns at active phase + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + // Type tab + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.row( + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.floatField("ability.knockbackUp", this::getKnockbackUp, this::setKnockbackUp) + ), + FieldDef.section("ability.section.beam"), + FieldDef.row( + FieldDef.floatField("ability.laserWidth", this::getLaserWidth, this::setLaserWidth), + FieldDef.floatField("ability.expansionSpeed", this::getExpansionSpeed, this::setExpansionSpeed) + ), + FieldDef.row( + FieldDef.intField("ability.lingerTicks", this::getLingerTicks, this::setLingerTicks), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + ), + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.section("ability.section.explosive"), + FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), + FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), + + // Visual tab + FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, this::getAnchorPointEnum, this::setAnchorPointEnum) + .tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", this::getAnchorOffsetX, this::setAnchorOffsetX), + FieldDef.floatField("ability.anchor.offsetY", this::getAnchorOffsetY, this::setAnchorOffsetY) + ).tab("ability.tab.visual"), + FieldDef.floatField("ability.anchor.offsetZ", this::getAnchorOffsetZ, this::setAnchorOffsetZ) + .tab("ability.tab.visual"), + FieldDef.section("ability.section.colors").tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor).tab("ability.tab.visual"), + FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled).tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), + FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual"), + FieldDef.section("ability.section.effects").tab("ability.tab.visual"), + FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect).tab("ability.tab.visual"), + FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .range(0.01f, 100f).visibleWhen(this::hasLightningEffect), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual") + )); } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java index 63c7c9005..17b878305 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityOrb.java @@ -12,37 +12,48 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import kamkeel.npcs.entity.EntityAbilityOrb; import kamkeel.npcs.util.AnchorPointHelper; -import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityOrb; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityOrb; -import noppes.npcs.entity.EntityNPCInterface; + +import java.util.Arrays; +import java.util.List; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; /** - * Orb ability: Spawns a homing projectile sphere that tracks target. - * The EntityAbilityOrb handles all movement, collision, and damage logic. - * This ability just configures and spawns the orb entity. + * Orb ability: Spawns homing projectile sphere(s) that track target. + * Supports 1-8 projectiles with shared visuals and per-projectile anchor points. */ public class AbilityOrb extends Ability implements IAbilityOrb { - // Ability-specific properties + private static final int MAX_PROJECTILES = 8; + + // Orb properties private float orbSize = 1.0f; - // Data classes for energy properties - public final EnergyColorData colorData = new EnergyColorData(); - public final EnergyCombatData combatData = new EnergyCombatData(); - public final EnergyHomingData homingData = new EnergyHomingData(); - public final EnergyLightningData lightningData = new EnergyLightningData(); - public final EnergyLifespanData lifespanData = new EnergyLifespanData(); - private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.RIGHT_HAND); + // Projectile count and fire stagger + private int projectileCount = 1; + private int fireDelay = 0; - // Transient state for orb entity (used during windup charging) - private transient EntityAbilityOrb orbEntity = null; + // Shared visual data (all projectiles use these) + private EnergyDisplayData displayData = new EnergyDisplayData(0xFFFFFF, 0xFF0000, true, 0.4f, 0.5f, 0.0f); + private EnergyLightningData lightningData = new EnergyLightningData(); + private EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + + // Shared combat/movement data + private final EnergyCombatData combatData = new EnergyCombatData(); + private final EnergyHomingData homingData = new EnergyHomingData(); + private final EnergyLifespanData lifespanData = new EnergyLifespanData(); + + // Per-projectile data (anchor + optional color override) + private ProjectileData[] projectiles; + + // Transient entity state + private transient EntityAbilityOrb[] orbEntities; public AbilityOrb() { this.typeId = "ability.cnpc.orb"; @@ -55,20 +66,100 @@ public class AbilityOrb extends Ability implements IAbilityOrb { this.lockMovement = LockMovementType.WINDUP; this.telegraphType = TelegraphType.CIRCLE; this.showTelegraph = true; - // Default built-in animation this.windUpAnimationName = "Ability_Orb_Windup"; this.activeAnimationName = "Ability_Orb_Active"; + initProjectiles(1); + } + + private void initProjectiles(int count) { + this.projectileCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + this.projectiles = new ProjectileData[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + projectiles[i] = new ProjectileData(getDefaultAnchor(i)); + } + } + + private AnchorPoint getDefaultAnchor(int index) { + switch (index) { + case 0: return AnchorPoint.RIGHT_HAND; + case 1: return AnchorPoint.LEFT_HAND; + default: return AnchorPoint.FRONT; + } + } + + public void setProjectileCount(int count) { + int newCount = Math.max(1, Math.min(count, MAX_PROJECTILES)); + if (newCount == projectileCount) return; + + ProjectileData[] oldProjectiles = projectiles; + initProjectiles(newCount); + + // Preserve existing projectile data + if (oldProjectiles != null) { + int copyCount = Math.min(oldProjectiles.length, newCount); + for (int i = 0; i < copyCount; i++) { + if (oldProjectiles[i] != null) projectiles[i] = oldProjectiles[i]; + } + } + } + + public int getProjectileCount() { + return projectileCount; + } + + public int getFireDelay() { + return fireDelay; + } + + public void setFireDelay(int delay) { + this.fireDelay = Math.max(0, delay); + } + + // Legacy compat + public int getDualFireDelay() { return fireDelay; } + public void setDualFireDelay(int delay) { setFireDelay(delay); } + + @Override + public List getVariants() { + return Arrays.asList( + new AbilityVariant("ability.variant.single", a -> { + a.setName("Orb"); + }), + new AbilityVariant("ability.variant.dual", a -> { + AbilityOrb orb = (AbilityOrb) a; + a.setName("Dual Orb"); + orb.setProjectileCount(2); + orb.setFireDelay(5); + a.setWindUpAnimationName("Ability_OrbDual_Windup"); + a.setActiveAnimationName("Ability_OrbDual_Active"); + }), + new AbilityVariant("ability.variant.barrage", a -> { + AbilityOrb orb = (AbilityOrb) a; + a.setName("Orb Barrage"); + orb.setOrbSize(0.5f); + orb.setDamage(4.0f); + orb.setKnockback(0.0f); + orb.setKnockbackUp(0.0f); + a.setMaxRange(75.0f); + a.setBurstEnabled(true); + a.setBurstAmount(15); + a.setBurstDelay(10); + a.setBurstReplayAnimations(false); + a.setBurstOverlap(true); + a.setWindUpAnimationName("Ability_BeamDual_Windup"); + a.setActiveAnimationName("Ability_BeamDual_Active"); + }) + ); } @Override - public boolean hasTypeSettings() { + public boolean allowOverlap() { return true; } @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityOrb(this, callback); + public boolean isReadyForBurstCompletion(int activeTick) { + return fireDelay <= 0 || activeTick >= fireDelay * (projectileCount - 1); } @Override @@ -81,71 +172,147 @@ public class AbilityOrb extends Ability implements IAbilityOrb { return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; } - @Override - public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { - signalCompletion(); - return; + /** + * Create orb entities. + * NPC: target is the aggro target — orbs will home toward it. + * Player: target is null — orbs fire in caster's look direction. + */ + private EntityAbilityOrb[] createOrbEntities(EntityLivingBase caster, EntityLivingBase target, World world) { + EntityAbilityOrb[] entities = new EntityAbilityOrb[projectileCount]; + for (int i = 0; i < projectileCount; i++) { + Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, projectiles[i].anchor); + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + entities[i] = new EntityAbilityOrb( + world, caster, target, + spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, + resolved, combatData, homingData, lightningData, lifespanData, trajectoryData); + entities[i].setEffects(this.effects); + entities[i].setSourceAbility(this); } - - // Start moving the orb that was spawned during windup - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.startMoving(target); + if (projectileCount == 2 && entities[0] != null && entities[1] != null) { + entities[0].setSiblingEntityId(entities[1].getEntityId()); + entities[1].setSiblingEntityId(entities[0].getEntityId()); } + return entities; + } - // Ability stays active until entity dies (prevents firing another while projectile is alive) - // Movement locking is handled separately by the base class + private void fireOrbEntity(EntityAbilityOrb orb, EntityLivingBase target) { + if (orb == null || orb.isDead) return; + if (isPreview()) { + orb.startPreviewFiring(); + } else { + orb.startMoving(target); + } } @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; - // Spawn orb in charging mode on first tick of windup if (tick == 1) { - // Create orb in charging mode - follows caster based on anchor point during windup - Vec3 spawnPos = AnchorPointHelper.calculateAnchorPosition(caster, anchorData); - orbEntity = new EntityAbilityOrb( - world, caster, target, - spawnPos.xCoord, spawnPos.yCoord, spawnPos.zCoord, orbSize, - colorData, combatData, homingData, lightningData, lifespanData); - orbEntity.setupCharging(anchorData, windUpTicks); + orbEntities = createOrbEntities(caster, target, world); + for (int i = 0; i < projectileCount; i++) { + EnergyDisplayData resolved = projectiles[i].resolveDisplay(displayData); + if (isPreview()) { + orbEntities[i].setupPreview(caster, orbSize, resolved, lightningData, projectiles[i].anchor, windUpTicks); + } else { + orbEntities[i].setupCharging(projectiles[i].anchor, windUpTicks); + } + spawnAbilityEntity(world, orbEntities[i]); + } + } + } - orbEntity.setEffects(this.effects); - world.spawnEntityInWorld(orbEntity); + @Override + public void onBurstRefire(EntityLivingBase caster, EntityLivingBase target, World world) { + orbEntities = createOrbEntities(caster, target, world); + for (EntityAbilityOrb orb : orbEntities) { + spawnAbilityEntity(world, orb); + } + for (EntityAbilityOrb orb : orbEntities) { + fireOrbEntity(orb, target); + } + } + + @Override + public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { + if (world.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (orbEntities == null) return; + + // Fire first projectile immediately + fireOrbEntity(orbEntities[0], target); + + // Fire remaining projectiles if no delay + if (fireDelay <= 0) { + for (int i = 1; i < projectileCount; i++) { + fireOrbEntity(orbEntities[i], target); + } } } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Signal completion when entity dies - if (orbEntity == null || orbEntity.isDead) { - orbEntity = null; + if (orbEntities == null) { + signalCompletion(); + return; + } + + // Fire staggered projectiles + if (fireDelay > 0) { + for (int i = 1; i < projectileCount; i++) { + if (tick == fireDelay * i) { + fireOrbEntity(orbEntities[i], target); + } + } + } + + // Check if all entities are dead + boolean allDead = true; + for (EntityAbilityOrb orb : orbEntities) { + if (orb != null && !orb.isDead) { + allDead = false; + break; + } + } + if (allDead) { signalCompletion(); } } @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - // Nothing to clean up - entity manages itself + } + + @Override + public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { + cleanup(); } @Override public void cleanup() { - // Despawn orb entity if still alive - if (orbEntity != null && !orbEntity.isDead) { - orbEntity.setDead(); + if (orbEntities != null) { + for (int i = 0; i < orbEntities.length; i++) { + if (orbEntities[i] != null && !orbEntities[i].isDead) { + orbEntities[i].setDead(); + } + orbEntities[i] = null; + } } - orbEntity = null; + orbEntities = null; } @Override public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) { - if (!showTelegraph || telegraphType == TelegraphType.NONE || target == null) { + // NPC: telegraph on aggro target position + // Player: no telegraph (orbs fire in look direction, no fixed position to mark) + if (!showTelegraph || telegraphType == TelegraphType.NONE || isPlayerCaster(caster) || target == null) { return null; } - // Create small circle telegraph at target position Telegraph telegraph = Telegraph.circle(orbSize * 1.5f); telegraph.setDurationTicks(windUpTicks); telegraph.setColor(windUpColor); @@ -153,7 +320,6 @@ public class AbilityOrb extends Ability implements IAbilityOrb { telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4)); telegraph.setHeightOffset(telegraphHeightOffset); - // Position at target and follow target during windup TelegraphInstance instance = new TelegraphInstance(telegraph, target.posX, target.posY, target.posZ, caster.rotationYaw); instance.setCasterEntityId(caster.getEntityId()); instance.setEntityIdToFollow(target.getEntityId()); @@ -169,253 +335,316 @@ public class AbilityOrb extends Ability implements IAbilityOrb { @Override public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("orbSize", orbSize); - anchorData.writeNBT(nbt); - colorData.writeNBT(nbt); + nbt.setInteger("projectileCount", projectileCount); + nbt.setInteger("fireDelay", fireDelay); + + // Shared visual data + displayData.writeNBT(nbt); + lightningData.writeNBT(nbt); + + // Shared combat/movement data combatData.writeNBT(nbt); homingData.writeNBT(nbt); - lightningData.writeNBT(nbt); lifespanData.writeNBT(nbt); - // Backward compat: old key was "orbSpeed" + + // Per-projectile data + for (int i = 0; i < projectileCount; i++) { + NBTTagCompound projNbt = new NBTTagCompound(); + projectiles[i].writeNBT(projNbt); + nbt.setTag("Projectile_" + i, projNbt); + } + + // Backward compat write nbt.setFloat("orbSpeed", homingData.speed); } @Override public void readTypeNBT(NBTTagCompound nbt) { this.orbSize = nbt.hasKey("orbSize") ? nbt.getFloat("orbSize") : 1.0f; - anchorData.readNBT(nbt); - colorData.readNBT(nbt); + + int count = nbt.hasKey("projectileCount") ? nbt.getInteger("projectileCount") : 1; + initProjectiles(count); + + // Read fireDelay with fallback to old dualFireDelay key + if (nbt.hasKey("fireDelay")) { + this.fireDelay = nbt.getInteger("fireDelay"); + } else if (nbt.hasKey("dualFireDelay")) { + this.fireDelay = nbt.getInteger("dualFireDelay"); + } else { + this.fireDelay = 0; + } + + // Shared combat/movement data combatData.readNBT(nbt); homingData.readNBT(nbt); - lightningData.readNBT(nbt); lifespanData.readNBT(nbt); - // Backward compat: old key was "orbSpeed" + + // Determine format and read accordingly + if (nbt.hasKey("Projectile_0")) { + NBTTagCompound proj0 = nbt.getCompoundTag("Projectile_0"); + if (proj0.hasKey("colorOverride")) { + // NEW format: shared visuals at root + ProjectileData per projectile + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + for (int i = 0; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + projectiles[i].readNBT(nbt.getCompoundTag("Projectile_" + i)); + } + } + } else { + // OLD format: full per-projectile arrays (displayData, lightningData, etc. in each Projectile_i) + // Read primary visuals from Projectile_0 + displayData.readNBT(proj0); + lightningData.readNBT(proj0); + projectiles[0].anchor.readNBT(proj0); + + // Read remaining projectiles, set color override if colors differ + for (int i = 1; i < projectileCount; i++) { + if (nbt.hasKey("Projectile_" + i)) { + NBTTagCompound projNbt = nbt.getCompoundTag("Projectile_" + i); + projectiles[i].anchor.readNBT(projNbt); + + // Check if this projectile had different colors + EnergyDisplayData tempDisplay = new EnergyDisplayData(); + tempDisplay.readNBT(projNbt); + if (tempDisplay.innerColor != displayData.innerColor || tempDisplay.outerColor != displayData.outerColor) { + projectiles[i].colorOverride = true; + projectiles[i].innerColor = tempDisplay.innerColor; + projectiles[i].outerColor = tempDisplay.outerColor; + } + } + } + } + } else { + // LEGACY flat format: all data at root level + displayData.readNBT(nbt); + lightningData.readNBT(nbt); + projectiles[0].anchor.readNBT(nbt); + } + + // Backward compat if (nbt.hasKey("orbSpeed")) { homingData.speed = nbt.getFloat("orbSpeed"); } } - // Getters & Setters - public float getOrbSpeed() { - return homingData.speed; + // ═══════════════════════════════════════════════════════════════════ + // API GETTERS & SETTERS + // ═══════════════════════════════════════════════════════════════════ + + public float getOrbSpeed() { return homingData.speed; } + public void setOrbSpeed(float speed) { homingData.speed = speed; } + + public float getOrbSize() { return orbSize; } + public void setOrbSize(float size) { this.orbSize = size; } + + public float getMaxDistance() { return lifespanData.maxDistance; } + public void setMaxDistance(float d) { lifespanData.maxDistance = d; } + + public int getMaxLifetime() { return lifespanData.maxLifetime; } + public void setMaxLifetime(int t) { lifespanData.maxLifetime = t; } + + public float getDamage() { return combatData.damage; } + public void setDamage(float d) { combatData.damage = d; } + + public float getKnockback() { return combatData.knockback; } + public void setKnockback(float k) { combatData.knockback = k; } + + public float getKnockbackUp() { return combatData.knockbackUp; } + public void setKnockbackUp(float k) { combatData.knockbackUp = k; } + + public boolean isHoming() { return homingData.homing; } + public void setHoming(boolean h) { homingData.homing = h; } + + public float getHomingStrength() { return homingData.homingStrength; } + public void setHomingStrength(float s) { homingData.homingStrength = s; } + + public float getHomingRange() { return homingData.homingRange; } + public void setHomingRange(float r) { homingData.homingRange = r; } + + public boolean isExplosive() { return combatData.explosive; } + public void setExplosive(boolean e) { combatData.explosive = e; } + + public float getExplosionRadius() { return combatData.explosionRadius; } + public void setExplosionRadius(float r) { combatData.explosionRadius = r; } + + public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + public void setExplosionDamageFalloff(float f) { combatData.explosionDamageFalloff = f; } + + // Shared display data (primary colors) + public int getInnerColor() { return displayData.innerColor; } + public void setInnerColor(int c) { displayData.innerColor = c; } + + public int getOuterColor() { return displayData.outerColor; } + public void setOuterColor(int c) { displayData.outerColor = c; } + + public float getOuterColorWidth() { return displayData.outerColorWidth; } + public void setOuterColorWidth(float w) { displayData.outerColorWidth = w; } + + public float getOuterColorAlpha() { return displayData.outerColorAlpha; } + public void setOuterColorAlpha(float a) { displayData.outerColorAlpha = a; } + + public boolean isOuterColorEnabled() { return displayData.outerColorEnabled; } + public void setOuterColorEnabled(boolean e) { displayData.outerColorEnabled = e; } + + public float getRotationSpeed() { return displayData.rotationSpeed; } + public void setRotationSpeed(float s) { displayData.rotationSpeed = s; } + + // Shared lightning data + public boolean hasLightningEffect() { return lightningData.lightningEffect; } + public void setLightningEffect(boolean e) { lightningData.lightningEffect = e; } + + public float getLightningDensity() { return lightningData.lightningDensity; } + public void setLightningDensity(float d) { lightningData.lightningDensity = d; } + + public float getLightningRadius() { return lightningData.lightningRadius; } + public void setLightningRadius(float r) { lightningData.lightningRadius = r; } + + public int getLightningFadeTime() { return lightningData.lightningFadeTime; } + public void setLightningFadeTime(int t) { lightningData.lightningFadeTime = t; } + + // Anchor - default to projectile 0 + public AnchorPoint getAnchorPointEnum() { return projectiles[0].anchor.anchorPoint; } + public void setAnchorPointEnum(AnchorPoint p) { projectiles[0].anchor.anchorPoint = p; } + + public float getAnchorOffsetX() { return projectiles[0].anchor.anchorOffsetX; } + public void setAnchorOffsetX(float x) { projectiles[0].anchor.anchorOffsetX = x; } + + public float getAnchorOffsetY() { return projectiles[0].anchor.anchorOffsetY; } + public void setAnchorOffsetY(float y) { projectiles[0].anchor.anchorOffsetY = y; } + + public float getAnchorOffsetZ() { return projectiles[0].anchor.anchorOffsetZ; } + public void setAnchorOffsetZ(float z) { projectiles[0].anchor.anchorOffsetZ = z; } + + public int getAnchorPoint() { return projectiles[0].anchor.anchorPoint.ordinal(); } + @Override + public void setAnchorPoint(int point) { projectiles[0].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + + // Indexed API methods + public int getInnerColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.innerColor : displayData.innerColor; + } + public void setInnerColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.innerColor = color; } - public void setOrbSpeed(float orbSpeed) { - homingData.speed = orbSpeed; + public int getOuterColor(int index) { + ProjectileData p = projectiles[clampIndex(index)]; + return p.colorOverride ? p.outerColor : displayData.outerColor; + } + public void setOuterColor(int index, int color) { + ProjectileData p = projectiles[clampIndex(index)]; + p.colorOverride = true; + p.outerColor = color; } - public float getOrbSize() { - return orbSize; - } + public int getAnchorPoint(int index) { return projectiles[clampIndex(index)].anchor.anchorPoint.ordinal(); } + public void setAnchorPoint(int index, int point) { projectiles[clampIndex(index)].anchor.anchorPoint = AnchorPoint.fromOrdinal(point); } + public void setAnchorOffsetX(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetX = offset; } + public void setAnchorOffsetY(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetY = offset; } + public void setAnchorOffsetZ(int index, float offset) { projectiles[clampIndex(index)].anchor.anchorOffsetZ = offset; } - public void setOrbSize(float orbSize) { - this.orbSize = orbSize; - } - - public float getMaxDistance() { - return lifespanData.maxDistance; - } - - public void setMaxDistance(float maxDistance) { - lifespanData.maxDistance = maxDistance; - } - - public int getMaxLifetime() { - return lifespanData.maxLifetime; - } - - public void setMaxLifetime(int maxLifetime) { - lifespanData.maxLifetime = maxLifetime; - } - - public float getDamage() { - return combatData.damage; - } - - public void setDamage(float damage) { - combatData.damage = damage; - } - - public float getKnockback() { - return combatData.knockback; - } - - public void setKnockback(float knockback) { - combatData.knockback = knockback; - } - - public float getKnockbackUp() { - return combatData.knockbackUp; - } - - public void setKnockbackUp(float knockbackUp) { - combatData.knockbackUp = knockbackUp; - } - - public boolean isHoming() { - return homingData.homing; - } - - public void setHoming(boolean homing) { - homingData.homing = homing; - } - - public float getHomingStrength() { - return homingData.homingStrength; - } - - public void setHomingStrength(float homingStrength) { - homingData.homingStrength = homingStrength; - } - - public float getHomingRange() { - return homingData.homingRange; - } - - public void setHomingRange(float homingRange) { - homingData.homingRange = homingRange; - } - - public boolean isExplosive() { - return combatData.explosive; - } - - public void setExplosive(boolean explosive) { - combatData.explosive = explosive; - } - - public float getExplosionRadius() { - return combatData.explosionRadius; - } - - public void setExplosionRadius(float explosionRadius) { - combatData.explosionRadius = explosionRadius; - } - - public float getExplosionDamageFalloff() { - return combatData.explosionDamageFalloff; - } - - public void setExplosionDamageFalloff(float explosionDamageFalloff) { - combatData.explosionDamageFalloff = explosionDamageFalloff; - } - - public int getInnerColor() { - return colorData.innerColor; - } - - public void setInnerColor(int innerColor) { - colorData.innerColor = innerColor; - } - - public int getOuterColor() { - return colorData.outerColor; - } - - public void setOuterColor(int outerColor) { - colorData.outerColor = outerColor; - } - - public float getOuterColorWidth() { - return colorData.outerColorWidth; - } - - public void setOuterColorWidth(float outerColorWidth) { - colorData.outerColorWidth = outerColorWidth; - } - - public float getOuterColorAlpha() { - return colorData.outerColorAlpha; - } - - public void setOuterColorAlpha(float outerColorAlpha) { - colorData.outerColorAlpha = outerColorAlpha; - } - - public boolean isOuterColorEnabled() { - return colorData.outerColorEnabled; - } - - public void setOuterColorEnabled(boolean outerColorEnabled) { - colorData.outerColorEnabled = outerColorEnabled; - } - - public float getRotationSpeed() { - return colorData.rotationSpeed; - } - - public void setRotationSpeed(float rotationSpeed) { - colorData.rotationSpeed = rotationSpeed; - } - - public boolean hasLightningEffect() { - return lightningData.lightningEffect; - } - - public void setLightningEffect(boolean lightningEffect) { - lightningData.lightningEffect = lightningEffect; - } - - public float getLightningDensity() { - return lightningData.lightningDensity; - } - - public void setLightningDensity(float lightningDensity) { - lightningData.lightningDensity = lightningDensity; - } - - public float getLightningRadius() { - return lightningData.lightningRadius; - } - - public void setLightningRadius(float lightningRadius) { - lightningData.lightningRadius = lightningRadius; - } - - public int getLightningFadeTime() { - return lightningData.lightningFadeTime; - } - - public void setLightningFadeTime(int lightningFadeTime) { - lightningData.lightningFadeTime = lightningFadeTime; - } - - public AnchorPoint getAnchorPointEnum() { return anchorData.anchorPoint; } - - public float getAnchorOffsetX() { return anchorData.anchorOffsetX; } - - public float getAnchorOffsetY() { return anchorData.anchorOffsetY; } - - public float getAnchorOffsetZ() { return anchorData.anchorOffsetZ; } - - public void setAnchorPointEnum(AnchorPoint anchorPoint) { this.anchorData.anchorPoint = anchorPoint; } - - public void setAnchorOffsetX(float x) { this.anchorData.anchorOffsetX = x; } - - public void setAnchorOffsetY(float y) { this.anchorData.anchorOffsetY = y; } - - public void setAnchorOffsetZ(float z) { this.anchorData.anchorOffsetZ = z; } - - public int getAnchorPoint() { - return anchorData.anchorPoint.ordinal(); + private int clampIndex(int index) { + return Math.max(0, Math.min(index, projectileCount - 1)); } @Override - public void setAnchorPoint(int point) { - this.anchorData.anchorPoint = AnchorPoint.fromOrdinal(point); - } - - @Override - @SideOnly(Side.CLIENT) - public Entity createPreviewEntity(EntityNPCInterface npc) { - if (npc == null || npc.worldObj == null) return null; - - EntityAbilityOrb orb = new EntityAbilityOrb(npc.worldObj); - orb.setupPreview(npc, orbSize, colorData, lightningData, anchorData, windUpTicks); - return orb; - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return lifespanData.maxLifetime > 0 ? Math.min(lifespanData.maxLifetime, 100) : 100; } + + // ═══════════════════════════════════════════════════════════════════ + // GUI FIELD DEFINITIONS + // ═══════════════════════════════════════════════════════════════════ + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + // Type tab - projectile count and fire delay + defs.add(FieldDef.row( + FieldDef.intField("ability.projectileCount", this::getProjectileCount, this::setProjectileCount).range(1, MAX_PROJECTILES), + FieldDef.intField("ability.fireDelay", this::getFireDelay, this::setFireDelay) + .range(0, 200).visibleWhen(() -> projectileCount > 1) + )); + + // Type tab - orb properties + defs.add(FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getOrbSpeed, this::setOrbSpeed) + )); + defs.add(FieldDef.row( + FieldDef.floatField("stats.size", this::getOrbSize, this::setOrbSize), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + )); + defs.add(FieldDef.row( + FieldDef.floatField("ability.maxDistance", this::getMaxDistance, this::setMaxDistance), + FieldDef.intField("ability.lifetime", this::getMaxLifetime, this::setMaxLifetime) + )); + defs.add(FieldDef.section("ability.section.homing")); + defs.add(FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing")); + defs.add(FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming)); + defs.add(FieldDef.section("ability.section.explosive")); + defs.add(FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive")); + defs.add(FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive)); + defs.add(AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects)); + + // Visual tab - shared primary colors + defs.add(FieldDef.section("ability.section.colors").tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual")); + defs.add(FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerAlpha", this::getOuterColorAlpha, this::setOuterColorAlpha) + .range(0, 1).visibleWhen(this::isOuterColorEnabled) + ).tab("ability.tab.visual")); + + // Visual tab - shared effects + defs.add(FieldDef.section("ability.section.effects").tab("ability.tab.visual")); + defs.add(FieldDef.floatField("ability.rotationSpeed", this::getRotationSpeed, this::setRotationSpeed) + .tab("ability.tab.visual")); + defs.add(FieldDef.boolField("ability.lightning", this::hasLightningEffect, this::setLightningEffect) + .tab("ability.tab.visual")); + defs.add(FieldDef.row( + FieldDef.floatField("gui.density", this::getLightningDensity, this::setLightningDensity) + .visibleWhen(this::hasLightningEffect).range(0.01f, 100f), + FieldDef.floatField("gui.radius", this::getLightningRadius, this::setLightningRadius) + .range(0.1f, 100f).visibleWhen(this::hasLightningEffect) + ).tab("ability.tab.visual")); + + // Visual tab - per-projectile sections + for (int i = 0; i < MAX_PROJECTILES; i++) { + final int idx = i; + String sectionKey = "ability.section.projectile" + (i + 1); + + defs.add(FieldDef.section(sectionKey).tab("ability.tab.visual") + .visibleWhen(() -> idx < projectileCount)); + + // Anchor point + defs.add(FieldDef.enumField("ability.anchorPoint", AnchorPoint.class, + () -> projectiles[idx].anchor.anchorPoint, v -> projectiles[idx].anchor.anchorPoint = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.row( + FieldDef.floatField("ability.anchor.offsetX", () -> projectiles[idx].anchor.anchorOffsetX, v -> projectiles[idx].anchor.anchorOffsetX = v), + FieldDef.floatField("ability.anchor.offsetY", () -> projectiles[idx].anchor.anchorOffsetY, v -> projectiles[idx].anchor.anchorOffsetY = v) + ).tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + defs.add(FieldDef.floatField("ability.anchor.offsetZ", () -> projectiles[idx].anchor.anchorOffsetZ, v -> projectiles[idx].anchor.anchorOffsetZ = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount)); + + // Color override (only when multiple projectiles) + defs.add(FieldDef.boolField("ability.colorOverride", () -> projectiles[idx].colorOverride, v -> projectiles[idx].colorOverride = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1)); + defs.add(FieldDef.colorSubGui("ability.innerColor", () -> projectiles[idx].innerColor, v -> projectiles[idx].innerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + defs.add(FieldDef.colorSubGui("ability.outerColor", () -> projectiles[idx].outerColor, v -> projectiles[idx].outerColor = v) + .tab("ability.tab.visual").visibleWhen(() -> idx < projectileCount && projectileCount > 1 && projectiles[idx].colorOverride)); + } + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java index c465bc0a5..8abd5d01e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityProjectile.java @@ -9,12 +9,16 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityProjectile; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; +import noppes.npcs.entity.EntityNPCInterface; + import noppes.npcs.api.ability.type.IAbilityProjectile; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; + +import java.util.Arrays; import java.util.List; /** @@ -48,14 +52,8 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityProjectile(this, callback); + public boolean allowBurst() { + return false; } @Override @@ -70,61 +68,129 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote || target == null) return; + if (world.isRemote && !isPreview()) { + signalCompletion(); + return; + } + + if (isPlayerCaster(caster)) { + // Player: instant hit-scan in look direction + executePlayerProjectile(caster, world); + } else if (target != null) { + // NPC: instant hit-scan on aggro target + executeNpcProjectile(caster, target, world); + } + + signalCompletion(); + } + + /** + * NPC projectile: instant hit-scan damage on the aggro target. + */ + private void executeNpcProjectile(EntityLivingBase caster, EntityLivingBase target, World world) { + if (isPreview()) return; - // Calculate direction to target double dx = target.posX - caster.posX; double dy = (target.posY + target.height / 2) - (caster.posY + caster.getEyeHeight()); double dz = target.posZ - caster.posZ; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { dx /= len; dy /= len; dz /= len; } - if (len > 0) { - dx /= len; - dy /= len; - dz /= len; - } - - // Deal instant damage with scripted event support - // TODO: Use custom EntityAbilityProjectile for actual tracking applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz); - - // Play sound world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); - // Handle splash damage for explosive projectiles if (explosive && explosionRadius > 0) { - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABBExcludingEntity(target, - target.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + applyExplosionDamage(caster, target, world, target.posX, target.posY, target.posZ); + } - for (Entity entity : entities) { - if (entity instanceof EntityLivingBase && entity != caster) { - EntityLivingBase living = (EntityLivingBase) entity; - float dist = target.getDistanceToEntity(living); - if (dist < explosionRadius) { - float falloff = 1.0f - (dist / explosionRadius); - // Apply splash damage with scripted event support (no knockback) - applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); - } - } - } + spawnProjectileParticles(world, caster, target); + } - // Explosion particles - world.playSoundAtEntity(target, "random.explode", 0.5f, 1.0f); - for (int i = 0; i < 10; i++) { - world.spawnParticle("explode", - target.posX + (world.rand.nextDouble() - 0.5) * explosionRadius, - target.posY + world.rand.nextDouble() * target.height, - target.posZ + (world.rand.nextDouble() - 0.5) * explosionRadius, - 0, 0.1, 0); + /** + * Player projectile: fires instant hit-scan in look direction. + * Raycasts for the first entity in range and applies damage. + */ + private void executePlayerProjectile(EntityLivingBase caster, World world) { + if (isPreview()) return; + + Vec3 look = caster.getLookVec(); + double eyeX = caster.posX; + double eyeY = caster.posY + caster.getEyeHeight(); + double eyeZ = caster.posZ; + + // Raycast: find the closest entity along look direction + EntityLivingBase hitTarget = null; + double closestDist = maxRange; + + @SuppressWarnings("unchecked") + List candidates = world.getEntitiesWithinAABBExcludingEntity(caster, + caster.boundingBox.expand(maxRange, maxRange, maxRange)); + + for (Entity entity : candidates) { + if (!(entity instanceof EntityLivingBase)) continue; + if (entity.isDead) continue; + + // Check if entity is roughly along look direction + double dx = entity.posX - eyeX; + double dy = (entity.posY + entity.height / 2) - eyeY; + double dz = entity.posZ - eyeZ; + double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (dist > maxRange || dist < 0.5) continue; + + // Dot product to check alignment with look vector + double dot = (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) / dist; + if (dot < 0.95) continue; // Must be within ~18 degree cone + + if (dist < closestDist) { + closestDist = dist; + hitTarget = (EntityLivingBase) entity; } } - // Spawn projectile particles (visual trail) - spawnProjectileParticles(world, caster, target); + world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f); - // Projectile is instant - signalCompletion(); + if (hitTarget != null) { + applyAbilityDamageWithDirection(caster, hitTarget, damage, knockback, look.xCoord, look.zCoord); + + if (explosive && explosionRadius > 0) { + applyExplosionDamage(caster, hitTarget, world, hitTarget.posX, hitTarget.posY, hitTarget.posZ); + } + + spawnProjectileParticles(world, caster, hitTarget); + } else { + // No hit — spawn particles along look direction anyway + spawnProjectileParticlesInDirection(world, caster, look); + } + } + + /** + * Apply explosion splash damage around a point. + */ + private void applyExplosionDamage(EntityLivingBase caster, EntityLivingBase primaryTarget, World world, + double x, double y, double z) { + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity(primaryTarget, + primaryTarget.boundingBox.expand(explosionRadius, explosionRadius, explosionRadius)); + + for (Entity entity : entities) { + if (entity instanceof EntityLivingBase && entity != caster) { + EntityLivingBase living = (EntityLivingBase) entity; + float dist = primaryTarget.getDistanceToEntity(living); + if (dist < explosionRadius) { + float falloff = 1.0f - (dist / explosionRadius); + applyAbilityDamage(caster, living, damage * falloff * 0.5f, 0); + } + } + } + + world.playSoundAtEntity(primaryTarget, "random.explode", 0.5f, 1.0f); + for (int i = 0; i < 10; i++) { + world.spawnParticle("explode", + x + (world.rand.nextDouble() - 0.5) * explosionRadius, + y + world.rand.nextDouble() * 2, + z + (world.rand.nextDouble() - 0.5) * explosionRadius, + 0, 0.1, 0); + } } private void spawnProjectileParticles(World world, EntityLivingBase caster, EntityLivingBase target) { @@ -158,6 +224,31 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { } } + /** + * Spawn projectile particles along a direction (player miss — no entity hit). + */ + private void spawnProjectileParticlesInDirection(World world, EntityLivingBase caster, Vec3 look) { + double startX = caster.posX; + double startY = caster.posY + caster.getEyeHeight(); + double startZ = caster.posZ; + + String particle = "flame"; + if (projectileType.equals("arrow")) { + particle = "crit"; + } else if (projectileType.equals("magic")) { + particle = "witchMagic"; + } + + int steps = (int) Math.max(5, maxRange * 2); + for (int i = 0; i < steps; i++) { + double progress = (double) i / steps * maxRange; + double px = startX + look.xCoord * progress; + double py = startY + look.yCoord * progress; + double pz = startZ + look.zCoord * progress; + world.spawnParticle(particle, px, py, pz, 0, 0, 0); + } + } + @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { // Projectile is instant, nothing to do per-tick @@ -256,4 +347,24 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile { public void setHomingStrength(float homingStrength) { this.homingStrength = homingStrength; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("stats.speed", this::getSpeed, this::setSpeed) + ), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + FieldDef.stringEnumField("ability.projectileType", new String[]{"fireball", "arrow", "magic"}, this::getProjectileType, this::setProjectileType), + FieldDef.section("ability.section.homing"), + FieldDef.boolField("gui.enabled", this::isHoming, this::setHoming).hover("ability.hover.homing"), + FieldDef.floatField("gui.strength", this::getHomingStrength, this::setHomingStrength).visibleWhen(this::isHoming), + FieldDef.section("ability.section.explosive"), + FieldDef.boolField("gui.enabled", this::isExplosive, this::setExplosive).hover("ability.hover.explosive"), + FieldDef.floatField("gui.radius", this::getExplosionRadius, this::setExplosionRadius).visibleWhen(this::isExplosive), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java index 6416cc0ba..6788a3ea3 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityShockwave.java @@ -11,13 +11,13 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityShockwave; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityShockwave; +import java.util.Arrays; import java.util.List; /** @@ -40,19 +40,10 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.cooldownTicks = 0; this.windUpTicks = 25; this.telegraphType = TelegraphType.CIRCLE; - this.windUpSound = "random.explode"; + this.windUpSound = "game.tnt.primed"; this.activeSound = "random.explode"; - } - - @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityShockwave(this, callback); + this.windUpAnimationName = "Ability_Shockwave_Windup"; + this.activeAnimationName = "Ability_Shockwave_Active"; } @Override @@ -72,58 +63,58 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Shockwave is instant - apply effect immediately after windup + if (!isPreview()) { + // Shockwave is instant - apply effect immediately after windup - // Get all entities in radius - AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + // Get all entities in radius + AxisAlignedBB box = caster.boundingBox.expand(pushRadius, pushRadius / 2, pushRadius); + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; + int count = 0; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; - double dist = caster.getDistanceToEntity(entity); - if (dist > pushRadius) continue; + double dist = caster.getDistanceToEntity(entity); + if (dist > pushRadius) continue; - count++; - if (count > maxTargets) break; + count++; + if (count > maxTargets) break; - // Calculate push direction (away from caster) - double dx = entity.posX - caster.posX; - double dz = entity.posZ - caster.posZ; - double len = Math.sqrt(dx * dx + dz * dz); + // Calculate push direction (away from caster) + double dx = entity.posX - caster.posX; + double dz = entity.posZ - caster.posZ; + double len = Math.sqrt(dx * dx + dz * dz); - if (len > 0) { - dx /= len; - dz /= len; - } else { - // Entity is directly on top of caster, push in random direction - double angle = Math.random() * Math.PI * 2; - dx = Math.cos(angle); - dz = Math.sin(angle); - } + if (len > 0) { + dx /= len; + dz /= len; + } else { + // Entity is directly on top of caster, push in random direction + double angle = Math.random() * Math.PI * 2; + dx = Math.cos(angle); + dz = Math.sin(angle); + } - // Scale knockback by distance (closer = stronger) - float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f; - float finalPush = pushStrength * distFactor; - // Apply damage with custom knockback direction - boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz); + // Scale knockback by distance (closer = stronger) + float distFactor = 1.0f - (float) (dist / pushRadius) * 0.5f; + float finalPush = pushStrength * distFactor; + // Apply damage with custom knockback direction + boolean wasHit = applyAbilityDamageWithDirection(caster, entity, damage * distFactor, finalPush, dx, dz); - // Apply effects if hit connected - if (wasHit) { - applyEffects(entity); + // Apply effects if hit connected + if (wasHit) { + applyEffects(entity); + } } } - - // Shockwave completes instantly - signalCompletion(); } @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Shockwave is instant - nothing to do per-tick + if (tick == 10) + signalCompletion(); } @Override @@ -175,4 +166,18 @@ public class AbilityShockwave extends Ability implements IAbilityShockwave { this.maxTargets = maxTargets; } + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.section("ability.section.push"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getPushRadius, this::setPushRadius), + FieldDef.floatField("gui.strength", this::getPushStrength, this::setPushStrength) + ), + FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java index 64e0255ca..a03ecdf6a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java @@ -13,13 +13,14 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilitySlam; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilitySlam; +import somehussar.gui.annotationHandling.GuiEditable; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; +import java.util.Arrays; import java.util.List; /** @@ -64,17 +65,6 @@ public class AbilitySlam extends Ability implements IAbilitySlam { this.activeAnimationName = "Ability_Slam_Active"; } - @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilitySlam(this, callback); - } - /** * Slam can be AOE_SELF (jump in place) or AOE_TARGET (leap to target). */ @@ -95,54 +85,114 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onWindUpTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { - // Update target position during windup - if (targetingMode == TargetingMode.AOE_SELF) { - // AOE_SELF: slam at caster's current position + if (isPlayerCaster(caster)) { + // Player: slam will launch from current position, no target tracking needed targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; - } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { - // AOE_TARGET: telegraph follows target via setEntityIdToFollow - targetX = target.posX; - targetY = target.posY; - targetZ = target.posZ; + } else { + // NPC: update target position during windup for telegraph tracking + if (targetingMode == TargetingMode.AOE_SELF) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { + targetX = target.posX; + targetY = target.posY; + targetZ = target.posZ; + } } } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - // Lock in the destination at moment of launch + hasLaunched = false; + hasLanded = false; + airTicks = 0; + caster.fallDistance = 0; + + if (isPlayerCaster(caster)) { + executePlayerSlam(caster); + } else { + executeNpcSlam(caster, target); + } + } + + /** + * NPC slam: Lock destination based on targeting mode, then launch in a ballistic arc toward it. + */ + private void executeNpcSlam(EntityLivingBase caster, EntityLivingBase target) { if (targetingMode == TargetingMode.AOE_SELF) { - // AOE_SELF: slam in place (just jump up) targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; } else if (targetingMode == TargetingMode.AOE_TARGET && target != null && !target.isDead) { - // AOE_TARGET: leap to target's current position targetX = target.posX; targetY = target.posY; targetZ = target.posZ; } else { - // Fallback: slam in place targetX = caster.posX; targetY = caster.posY; targetZ = caster.posZ; } - - hasLaunched = false; - hasLanded = false; - airTicks = 0; - - // Reset fall distance to prevent fall damage during slam - caster.fallDistance = 0; - - // Calculate and apply leap velocity launchTowardTarget(caster); } + /** + * Player slam: Launch straight up. Player controls horizontal movement via WASD. + * AOE damage triggers wherever the player lands. + */ + private void executePlayerSlam(EntityLivingBase caster) { + targetX = caster.posX; + targetY = caster.posY; + targetZ = caster.posZ; + + double vy = calculateLaunchVelocity(Math.max(1.0, leapHeight)); + caster.motionY = vy; + hasLaunched = true; + caster.velocityChanged = true; + } + + /** + * Calculate the initial vertical velocity needed to reach a target height + * in Minecraft's physics (gravity=0.08, vertical drag=0.98). + * Uses iterative simulation since the drag makes a closed-form solution impractical. + */ + private static double calculateLaunchVelocity(double targetHeight) { + // Binary search for the initial velocity that reaches targetHeight + double lo = 0.0, hi = 10.0; + for (int iter = 0; iter < 30; iter++) { + double mid = (lo + hi) / 2.0; + double maxY = simulateMaxHeight(mid); + if (maxY < targetHeight) { + lo = mid; + } else { + hi = mid; + } + } + return (lo + hi) / 2.0; + } + + /** + * Simulate Minecraft vertical physics to find peak height reached + * with a given initial upward velocity. + */ + private static double simulateMaxHeight(double vy) { + double y = 0; + double maxY = 0; + for (int t = 0; t < 200 && vy > 0; t++) { + y += vy; + vy -= 0.08; // gravity + vy *= 0.98; // vertical drag + if (y > maxY) maxY = y; + } + return maxY; + } + /** * Calculate ballistic arc and launch caster toward target. - * Accounts for Minecraft's drag physics to actually reach the destination. + * leapHeight = exact peak height in blocks above launch point. + * leapSpeed = velocity multiplier (faster motion, same height). */ private void launchTowardTarget(EntityLivingBase caster) { double dx = targetX - caster.posX; @@ -150,17 +200,23 @@ public class AbilitySlam extends Ability implements IAbilitySlam { double dz = targetZ - caster.posZ; double horizontalDist = Math.sqrt(dx * dx + dz * dz); + // Calculate vertical velocity to reach exact leapHeight + double arcHeight = Math.max(1.0, leapHeight); + double vy = calculateLaunchVelocity(arcHeight); + // For AOE_SELF or very close targets, just hop in place if (horizontalDist < 0.5) { caster.motionX = 0; caster.motionZ = 0; - caster.motionY = 0.8 * leapSpeed; + caster.motionY = vy; hasLaunched = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(true); } - caster.velocityChanged = true; - caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); + if (!isPreview()) { + caster.velocityChanged = true; + caster.worldObj.playSoundAtEntity(caster, "mob.irongolem.throw", 0.8f, 0.8f); + } return; } @@ -174,8 +230,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { targetZ = caster.posZ + dz; } - // Choose flight time based on distance - shorter distances = faster - int flightTicks = (int) Math.max(15, Math.min(horizontalDist * 1.5, 30)); + // Choose flight time based on distance, scaled by speed (faster = fewer ticks) + double speedFactor = Math.max(0.1, leapSpeed); + int flightTicks = (int) Math.max(10, Math.min(horizontalDist * 1.5 / speedFactor, 40)); // Minecraft applies drag of 0.91 per tick to horizontal motion in air // Total distance traveled with initial velocity v0 over n ticks: @@ -185,34 +242,13 @@ public class AbilitySlam extends Ability implements IAbilitySlam { double dragPowN = Math.pow(drag, flightTicks); double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN); - // Scale by leap speed - vHorizontal *= leapSpeed; - - // Vertical velocity calculation: - // Minecraft gravity is 0.08 per tick, with 0.98 drag on vertical motion - // For a nice arc, we want to peak roughly in the middle of the flight - double gravity = 0.08; - double verticalDrag = 0.98; - - // Calculate required upward velocity to create a nice arc and land at target height - // Peak height should be proportional to horizontal distance for visual appeal - double arcHeight = Math.max(1.0, leapHeight) * leapSpeed; - - // Approximate the required initial vertical velocity - // Account for gravity and drag - use a simplified model - double peakTicks = flightTicks * 0.4; // Peak around 40% through flight - double vy = (arcHeight * 2.0 / peakTicks) + (gravity * peakTicks * 0.5); - - // Adjust for height difference + // Adjust vertical velocity for height difference between start and target if (dy > 0) { vy += dy / flightTicks * 1.5; // Going up - need more velocity } else if (dy < 0) { vy += dy / flightTicks * 0.3; // Going down - gravity helps } - // Ensure minimum upward velocity for visible jump - vy = Math.max(vy, 0.6 * leapSpeed); - // Normalize horizontal direction and apply velocity double dirX = dx / horizontalDist; double dirZ = dz / horizontalDist; @@ -222,16 +258,17 @@ public class AbilitySlam extends Ability implements IAbilitySlam { caster.motionY = vy; hasLaunched = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(true); } - caster.velocityChanged = true; + if (!isPreview()) { + caster.velocityChanged = true; + } // Face the target float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); caster.rotationYaw = targetYaw; caster.rotationYawHead = targetYaw; - } @Override @@ -242,7 +279,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { airTicks++; // Continuously reset fall distance during slam to prevent fall damage - caster.fallDistance = 0; + if (!isPreview()) { + caster.fallDistance = 0; + } // Check for landing if (caster.onGround && airTicks > 3) { @@ -257,12 +296,15 @@ public class AbilitySlam extends Ability implements IAbilitySlam { return; } - // While in air, face toward target - double dx = targetX - caster.posX; - double dz = targetZ - caster.posZ; - float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); - caster.rotationYaw = targetYaw; - caster.rotationYawHead = targetYaw; + // NPC: face toward target destination while in air + // Player: free look — player controls their own camera + if (!isPreview() && !isPlayerCaster(caster)) { + double dx = targetX - caster.posX; + double dz = targetZ - caster.posZ; + float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); + caster.rotationYaw = targetYaw; + caster.rotationYawHead = targetYaw; + } } /** @@ -270,22 +312,25 @@ public class AbilitySlam extends Ability implements IAbilitySlam { */ private void onLanding(EntityLivingBase caster, World world) { hasLanded = true; - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } // Signal that the ability has completed its active phase signalCompletion(); - // Reset fall distance to prevent fall damage on landing - caster.fallDistance = 0; - // Stop horizontal momentum caster.motionX = 0; caster.motionZ = 0; - caster.velocityChanged = true; - if (world.isRemote) return; + if (!isPreview()) { + // Reset fall distance to prevent fall damage on landing + caster.fallDistance = 0; + caster.velocityChanged = true; + } + + if (world.isRemote && !isPreview()) return; + if (isPreview()) return; // Play slam impact sound on landing world.playSoundAtEntity(caster, "random.explode", 1.0f, 1.0f); @@ -351,7 +396,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onComplete(EntityLivingBase caster, EntityLivingBase target) { - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } hasLaunched = false; @@ -361,7 +406,7 @@ public class AbilitySlam extends Ability implements IAbilitySlam { @Override public void onInterrupt(EntityLivingBase caster, DamageSource source, float damage) { - if (caster instanceof EntityNPCInterface) { + if (!isPreview() && caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(false); } hasLaunched = false; @@ -377,97 +422,8 @@ public class AbilitySlam extends Ability implements IAbilitySlam { airTicks = 0; } - // ==================== PREVIEW MODE ==================== - - private transient double previewVelX, previewVelY, previewVelZ; - private transient boolean previewLaunched = false; - private transient double previewGroundY; - @Override - @SideOnly(Side.CLIENT) - public void onPreviewExecute(EntityNPCInterface npc) { - previewLaunched = false; - - double tx, ty, tz; - if (previewTarget != null && targetingMode == TargetingMode.AOE_TARGET) { - tx = previewTarget.posX; - ty = previewTarget.posY; - tz = previewTarget.posZ; - } else { - tx = npc.posX; - ty = npc.posY; - tz = npc.posZ; - } - - previewGroundY = npc.posY; - - double dx = tx - npc.posX; - double dz = tz - npc.posZ; - double horizontalDist = Math.sqrt(dx * dx + dz * dz); - - if (horizontalDist < 0.5) { - previewVelX = 0; - previewVelZ = 0; - previewVelY = 0.8 * leapSpeed; - } else { - if (horizontalDist > maxRange) { - double scale = maxRange / horizontalDist; - dx *= scale; - dz *= scale; - horizontalDist = maxRange; - } - - int flightTicks = (int) Math.max(15, Math.min(horizontalDist * 1.5, 30)); - double drag = 0.91; - double dragPowN = Math.pow(drag, flightTicks); - double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN) * leapSpeed; - - double arcHeight = Math.max(1.0, leapHeight) * leapSpeed; - double peakTicks = flightTicks * 0.4; - double vy = (arcHeight * 2.0 / peakTicks) + (0.08 * peakTicks * 0.5); - vy = Math.max(vy, 0.6 * leapSpeed); - - double dirX = dx / horizontalDist; - double dirZ = dz / horizontalDist; - previewVelX = dirX * vHorizontal; - previewVelZ = dirZ * vHorizontal; - previewVelY = vy; - } - previewLaunched = true; - } - - @Override - @SideOnly(Side.CLIENT) - public void onPreviewActiveTick(EntityNPCInterface npc, int tick) { - if (!previewLaunched) return; - - // Apply velocity - npc.prevPosX = npc.posX; - npc.prevPosY = npc.posY; - npc.prevPosZ = npc.posZ; - - npc.posX += previewVelX; - npc.posY += previewVelY; - npc.posZ += previewVelZ; - - // Gravity and drag - previewVelY -= 0.08; - previewVelY *= 0.98; - previewVelX *= 0.91; - previewVelZ *= 0.91; - - // Ground clamp - stop falling below starting Y - if (npc.posY < previewGroundY && previewVelY < 0) { - npc.posY = previewGroundY; - previewVelY = 0; - previewVelX = 0; - previewVelZ = 0; - previewLaunched = false; - } - } - - @Override - public int getPreviewActiveDuration() { + public int getMaxPreviewDuration() { return 60; } @@ -509,11 +465,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam { TelegraphInstance instance = new TelegraphInstance(telegraph, targetX, groundY, targetZ, caster.rotationYaw); instance.setCasterEntityId(caster.getEntityId()); - // AOE_TARGET: telegraph follows target during windup - if (targetingMode == TargetingMode.AOE_TARGET && target != null) { + // NPC AOE_TARGET: telegraph follows target during windup + // Player: telegraph stays at caster position (no target to follow) + if (!isPlayerCaster(caster) && targetingMode == TargetingMode.AOE_TARGET && target != null) { instance.setEntityIdToFollow(target.getEntityId()); } - // AOE_SELF: telegraph stays at caster position, no follow return instance; } @@ -581,4 +537,22 @@ public class AbilitySlam extends Ability implements IAbilitySlam { public void setLeapHeight(float leapHeight) { this.leapHeight = leapHeight; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getRadius, this::setRadius), + FieldDef.floatField("ability.knockback", this::getKnockbackStrength, this::setKnockbackStrength) + ), + FieldDef.section("ability.section.leap"), + FieldDef.row( + FieldDef.floatField("gui.speed", this::getLeapSpeed, this::setLeapSpeed), + FieldDef.floatField("gui.height", this::getLeapHeight, this::setLeapHeight) + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java index d2acc4df3..8638dd2a4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySweeper.java @@ -5,7 +5,9 @@ import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.ability.data.EnergyColorData; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import kamkeel.npcs.controllers.data.telegraph.Telegraph; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; @@ -13,12 +15,11 @@ import kamkeel.npcs.entity.EntityAbilitySweeper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import noppes.npcs.LogWriter; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilitySweeper; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.api.ability.type.IAbilitySweeper; +import java.util.Arrays; +import java.util.List; + /** * Sweeper ability: A low sweeping beam that rotates around the NPC. * Players can jump over it. The beam completes a set number of rotations before ending. @@ -41,7 +42,7 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { private boolean lockOnTarget = false; // Visual properties - private EnergyColorData colorData = new EnergyColorData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f); + private EnergyDisplayData colorData = new EnergyDisplayData(0xFF6600, 0xFF0000, true, 1.8f, 0.5f, 0.0f); // Runtime state (transient) private transient EntityAbilitySweeper activeEntity = null; @@ -61,14 +62,8 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { } @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilitySweeper(this, callback); + public boolean allowBurst() { + return false; } @Override @@ -83,19 +78,26 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) { + if (world.isRemote && !isPreview()) { signalCompletion(); return; } - // Spawn the entity that handles BOTH visuals AND damage + // Spawn the sweeper entity that handles BOTH visuals AND damage. + // NPC: target is the aggro target — lockOnTarget tracks it during sweep. + // Player: target is null — sweep rotates around caster's facing direction, lockOnTarget has no effect. activeEntity = new EntityAbilitySweeper(world, caster, target, beamLength, beamWidth, beamHeight, colorData, sweepSpeed, numberOfRotations, damage, damageInterval, piercing, lockOnTarget); - world.spawnEntityInWorld(activeEntity); + + if (isPreview()) { + activeEntity.setupPreview(caster); + } + + spawnAbilityEntity(world, activeEntity); // Ability stays active until entity dies (prevents firing another while projectile is alive) // Movement locking is handled separately by the base class @@ -110,6 +112,11 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { } } + @Override + public void onInterrupt(EntityLivingBase caster, net.minecraft.util.DamageSource source, float damage) { + cleanup(); + } + @Override public void cleanup() { // Clean up entity if still alive @@ -204,4 +211,49 @@ public class AbilitySweeper extends Ability implements IAbilitySweeper { public void setOuterColorWidth(float outerColorWidth) { colorData.outerColorWidth = outerColorWidth; } public boolean isOuterColorEnabled() { return colorData.outerColorEnabled; } public void setOuterColorEnabled(boolean outerColorEnabled) { colorData.outerColorEnabled = outerColorEnabled; } + + @Override + public int getMaxPreviewDuration() { + return (int) ((360.0f * numberOfRotations) / sweepSpeed) + 10; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.intField("ability.damageInterval", this::getDamageInterval, this::setDamageInterval) + ), + FieldDef.section("ability.section.beam"), + FieldDef.row( + FieldDef.floatField("gui.length", this::getBeamLength, this::setBeamLength), + FieldDef.floatField("gui.width", this::getBeamWidth, this::setBeamWidth) + ), + FieldDef.row( + FieldDef.floatField("gui.height", this::getBeamHeight, this::setBeamHeight), + FieldDef.floatField("ability.sweepSpeed", this::getSweepSpeed, this::setSweepSpeed) + ), + FieldDef.intField("ability.rotations", this::getNumberOfRotations, this::setNumberOfRotations), + FieldDef.row( + FieldDef.boolField("ability.piercing", this::isPiercing, this::setPiercing) + .hover("ability.hover.piercing"), + FieldDef.boolField("ability.lockTarget", this::isLockOnTarget, this::setLockOnTarget) + .hover("ability.hover.lockTarget") + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects), + + // Visual tab + FieldDef.section("ability.section.colors").tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.innerColor", this::getInnerColor, this::setInnerColor) + .tab("ability.tab.visual"), + FieldDef.boolField("ability.outerEnabled", this::isOuterColorEnabled, this::setOuterColorEnabled) + .tab("ability.tab.visual"), + FieldDef.colorSubGui("ability.outerColor", this::getOuterColor, this::setOuterColor) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled), + FieldDef.floatField("ability.outerWidth", this::getOuterColorWidth, this::setOuterColorWidth) + .tab("ability.tab.visual").visibleWhen(this::isOuterColorEnabled) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java index 4e4a5dff7..8e09c43e7 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTeleport.java @@ -1,10 +1,9 @@ package kamkeel.npcs.controllers.data.ability.type; -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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -14,13 +13,17 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityTeleport; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilityTeleport; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Arrays; import java.util.List; import java.util.Random; @@ -35,7 +38,17 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { public enum TeleportMode { BLINK, BEHIND, - SINGLE + SINGLE; + + @Override + public String toString() { + switch (this) { + case BLINK: return "ability.teleport.blink"; + case BEHIND: return "ability.teleport.behind"; + case SINGLE: return "ability.teleport.single"; + default: return name(); + } + } } private static final Random RANDOM = new Random(); @@ -60,6 +73,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { this.typeId = "ability.cnpc.teleport"; this.name = "Teleport"; this.targetingMode = TargetingMode.AGGRO_TARGET; + this.allowedBy = UserType.NPC_ONLY; this.maxRange = 30.0f; this.minRange = 5.0f; this.cooldownTicks = 0; @@ -73,15 +87,8 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui( - IAbilityConfigCallback callback) { - return new SubGuiAbilityTeleport(this, callback); + public boolean hasDamage() { + return false; } @Override @@ -123,7 +130,7 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } private void performBlink(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote) return; + if (world.isRemote && !isPreview()) return; double oldX = caster.posX; double oldY = caster.posY; @@ -132,36 +139,47 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { Vec3 destination = calculateDestination(caster, target, world); if (destination == null) return; - boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight; - if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ, - destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) { - destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ, + if (!isPreview()) { + boolean mustHaveLOS = mode == TeleportMode.BEHIND || requireLineOfSight; + if (mustHaveLOS && !hasLineOfSight(world, oldX, oldY + caster.getEyeHeight(), oldZ, + destination.xCoord, destination.yCoord + caster.getEyeHeight(), destination.zCoord)) { + destination = findValidPositionAlongLine(world, caster, oldX, oldY, oldZ, + destination.xCoord, destination.yCoord, destination.zCoord); + if (destination == null) return; + } + + destination = findSafeDestination(world, oldX, oldY, oldZ, destination.xCoord, destination.yCoord, destination.zCoord); if (destination == null) return; + + // Damage at origin + if (damageAtStart) { + dealDamageAt(caster, world, oldX, oldY, oldZ); + } + + // Spawn particles at origin + spawnTeleportParticles(world, oldX, oldY, oldZ); } - destination = findSafeDestination(world, oldX, oldY, oldZ, - destination.xCoord, destination.yCoord, destination.zCoord); - if (destination == null) return; - - // Damage at origin - if (damageAtStart) { - dealDamageAt(caster, world, oldX, oldY, oldZ); - } - - // Spawn particles at origin - spawnTeleportParticles(world, oldX, oldY, oldZ); - // Teleport - caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord); + if (isPreview()) { + caster.setPosition(destination.xCoord, destination.yCoord, destination.zCoord); + caster.prevPosX = destination.xCoord; + caster.prevPosY = destination.yCoord; + caster.prevPosZ = destination.zCoord; + } else { + caster.setPositionAndUpdate(destination.xCoord, destination.yCoord, destination.zCoord); + } caster.fallDistance = 0; - // Spawn particles at destination - spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord); + if (!isPreview()) { + // Spawn particles at destination + spawnTeleportParticles(world, destination.xCoord, destination.yCoord, destination.zCoord); - // Damage at destination - if (damageAtEnd) { - dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord); + // Damage at destination + if (damageAtEnd) { + dealDamageAt(caster, world, destination.xCoord, destination.yCoord, destination.zCoord); + } } // Face target after teleport @@ -212,26 +230,8 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { } } - // No target (player use) - teleport in caster's look direction - Vec3 look = caster.getLookVec(); - switch (mode) { - case BEHIND: - // Teleport forward in look direction by behindDistance - newX = caster.posX + look.xCoord * behindDistance; - newZ = caster.posZ + look.zCoord * behindDistance; - newY = caster.posY; - return Vec3.createVectorHelper(newX, newY, newZ); - case SINGLE: - case BLINK: - default: - // Teleport forward in look direction within blinkRadius - double dist = Math.min(blinkRadius, maxRange); - double offset = (RANDOM.nextDouble() * 0.5 + 0.5) * dist; // 50-100% of max distance - newX = caster.posX + look.xCoord * offset; - newZ = caster.posZ + look.zCoord * offset; - newY = caster.posY; - return Vec3.createVectorHelper(newX, newY, newZ); - } + // NPC-only ability — should not reach here + return null; } private Vec3 findSafeDestination(World world, double oldX, double oldY, double oldZ, @@ -555,4 +555,43 @@ public class AbilityTeleport extends Ability implements IAbilityTeleport { public void setDamageRadius(float damageRadius) { this.damageRadius = damageRadius; } + + @Override + public int getMaxPreviewDuration() { + int blinkLimit = mode == TeleportMode.BLINK ? blinkCount : 1; + return blinkLimit * blinkDelayTicks + 10; + } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.enumField("ability.mode", TeleportMode.class, this::getModeEnum, this::setModeEnum), + FieldDef.floatField("ability.blinkRadius", this::getBlinkRadius, this::setBlinkRadius) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK || this.getModeEnum() == TeleportMode.SINGLE), + FieldDef.row( + FieldDef.intField("ability.blinkCount", this::getBlinkCount, this::setBlinkCount) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK), + FieldDef.intField("ability.blinkDelay", this::getBlinkDelayTicks, this::setBlinkDelayTicks) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK) + ), + FieldDef.floatField("ability.behindDistance", this::getBehindDistance, this::setBehindDistance) + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BEHIND), + FieldDef.boolField("ability.lineOfSight", this::isRequireLineOfSight, this::setRequireLineOfSight) + .hover("ability.hover.lineOfSight") + .visibleWhen(() -> this.getModeEnum() == TeleportMode.BLINK || this.getModeEnum() == TeleportMode.SINGLE), + FieldDef.section("ability.section.damage"), + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("gui.radius", this::getDamageRadius, this::setDamageRadius) + ), + FieldDef.row( + FieldDef.boolField("ability.damageAtStart", this::isDamageAtStart, this::setDamageAtStart) + .hover("ability.hover.dmgAtStart"), + FieldDef.boolField("ability.damageAtEnd", this::isDamageAtEnd, this::setDamageAtEnd) + .hover("ability.hover.dmgAtEnd") + ), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java index a50fe57a1..494192e04 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityTrap.java @@ -1,10 +1,9 @@ package kamkeel.npcs.controllers.data.ability.type; -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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; +import kamkeel.npcs.controllers.data.ability.UserType; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; import net.minecraft.entity.EntityLivingBase; @@ -12,13 +11,17 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityTrap; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.api.ability.type.IAbilityTrap; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -34,7 +37,17 @@ public class AbilityTrap extends Ability implements IAbilityTrap { public enum TrapPlacement { AT_CASTER, AT_TARGET, - AHEAD_OF_CASTER + AHEAD_OF_CASTER; + + @Override + public String toString() { + switch (this) { + case AT_CASTER: return "ability.trapPlace.atCaster"; + case AT_TARGET: return "ability.trapPlace.atTarget"; + case AHEAD_OF_CASTER: return "ability.trapPlace.aheadOfCaster"; + default: return name(); + } + } } private int durationTicks = 200; @@ -71,17 +84,12 @@ public class AbilityTrap extends Ability implements IAbilityTrap { this.cooldownTicks = 0; this.windUpTicks = 20; this.telegraphType = TelegraphType.CIRCLE; + this.allowedBy = UserType.NPC_ONLY; } @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui(IAbilityConfigCallback callback) { - return new SubGuiAbilityTrap(this, callback); + public boolean allowBurst() { + return false; } @Override @@ -122,7 +130,6 @@ public class AbilityTrap extends Ability implements IAbilityTrap { } break; case AT_TARGET: - // Telegraph follows target during windup, locks on execute if (target != null) { instance.setEntityIdToFollow(target.getEntityId()); } @@ -148,14 +155,12 @@ public class AbilityTrap extends Ability implements IAbilityTrap { trapZ = caster.posZ; break; case AT_TARGET: - // Use telegraph position with offset if (telegraph != null) { double[] pos = Ability.calculateOffsetPosition(telegraph.getX(), telegraph.getY(), telegraph.getZ(), minOffset, maxOffset, randomOffset, RANDOM); trapX = pos[0]; trapY = pos[1]; trapZ = pos[2]; - // Update telegraph to show actual trap position telegraph.setX(trapX); telegraph.setY(trapY); telegraph.setZ(trapZ); @@ -206,26 +211,28 @@ public class AbilityTrap extends Ability implements IAbilityTrap { return; } - AxisAlignedBB box = AxisAlignedBB.getBoundingBox( - trapX - triggerRadius, trapY - 1, trapZ - triggerRadius, - trapX + triggerRadius, trapY + 2, trapZ + triggerRadius - ); + if (!isPreview()) { + AxisAlignedBB box = AxisAlignedBB.getBoundingBox( + trapX - triggerRadius, trapY - 1, trapZ - triggerRadius, + trapX + triggerRadius, trapY + 2, trapZ + triggerRadius + ); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; - if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; + if (maxTriggers == 1 && triggeredEntities.contains(entity.getUniqueID())) continue; - double dx = entity.posX - trapX; - double dz = entity.posZ - trapZ; - double dist = Math.sqrt(dx * dx + dz * dz); + double dx = entity.posX - trapX; + double dz = entity.posZ - trapZ; + double dist = Math.sqrt(dx * dx + dz * dz); - if (dist <= triggerRadius) { - triggerTrap(caster, entity, world); - return; + if (dist <= triggerRadius) { + triggerTrap(caster, entity, world); + return; + } } } } @@ -464,4 +471,31 @@ public class AbilityTrap extends Ability implements IAbilityTrap { public boolean isArmed() { return armed; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks) + .range(1, 2000), + FieldDef.enumField("ability.placement", TrapPlacement.class, this::getPlacementEnum, this::setPlacementEnum) + .hover("ability.hover.placement"), + FieldDef.section("ability.section.trigger"), + FieldDef.row( + FieldDef.floatField("gui.radius", this::getTriggerRadius, this::setTriggerRadius), + FieldDef.intField("ability.armTime", this::getArmTime, this::setArmTime) + ), + FieldDef.row( + FieldDef.intField("ability.maxTriggers", this::getMaxTriggers, this::setMaxTriggers), + FieldDef.intField("ability.triggerCooldown", this::getTriggerCooldown, this::setTriggerCooldown) + ), + FieldDef.section("ability.section.damage"), + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("gui.radius", this::getDamageRadius, this::setDamageRadius) + ), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index f289f0f72..90aaf054b 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -1,7 +1,5 @@ package kamkeel.npcs.controllers.data.ability.type; -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.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; @@ -10,13 +8,16 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; -import noppes.npcs.client.gui.advanced.ability.SubGuiAbilityVortex; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.client.gui.builder.FieldDef; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityVortex; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -62,18 +63,6 @@ public class AbilityVortex extends Ability implements IAbilityVortex { this.activeSound = "mob.ghast.fireball"; } - @Override - public boolean hasTypeSettings() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public SubGuiAbilityConfig createConfigGui( - IAbilityConfigCallback callback) { - return new SubGuiAbilityVortex(this, callback); - } - @Override public boolean isTargetingModeLocked() { return true; @@ -95,29 +84,32 @@ public class AbilityVortex extends Ability implements IAbilityVortex { pullComplete = false; ticksSincePullDamage = 0; - if (aoe) { - AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); - @SuppressWarnings("unchecked") - List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); + if (!isPreview()) { + if (aoe) { + AxisAlignedBB box = caster.boundingBox.expand(pullRadius, pullRadius / 2, pullRadius); + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, box); - int count = 0; - for (EntityLivingBase entity : entities) { - if (entity == caster) continue; - if (entity.isDead) continue; + int count = 0; + for (EntityLivingBase entity : entities) { + if (entity == caster) continue; + if (entity.isDead) continue; - double dist = caster.getDistanceToEntity(entity); - if (dist <= pullRadius) { - getPulledEntities().add(entity.getUniqueID()); - count++; - if (count >= maxTargets) break; + double dist = caster.getDistanceToEntity(entity); + if (dist <= pullRadius) { + getPulledEntities().add(entity.getUniqueID()); + count++; + if (count >= maxTargets) break; + } } - } - } else { - // Single target mode - still check pullRadius - if (target != null && !target.isDead) { - double dist = caster.getDistanceToEntity(target); - if (dist <= pullRadius) { - getPulledEntities().add(target.getUniqueID()); + } else { + // NPC single-target mode: pull the aggro target + // Player: single-target mode has no effect (no target to pull — use AOE mode instead) + if (!isPlayerCaster(caster) && target != null && !target.isDead) { + double dist = caster.getDistanceToEntity(target); + if (dist <= pullRadius) { + getPulledEntities().add(target.getUniqueID()); + } } } } @@ -125,6 +117,12 @@ public class AbilityVortex extends Ability implements IAbilityVortex { @Override public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { + if (isPreview()) { + // No entities to pull in preview, just run animation for a duration + if (tick >= 60) signalCompletion(); + return; + } + if (pullComplete || getPulledEntities().isEmpty()) { signalCompletion(); return; @@ -149,7 +147,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double dz = destZ - entity.posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist <= 1.0f) { + if (dist <= 1.5f) { getPulledEntities().remove(uuid); onTargetArrived(caster, entity, world); continue; @@ -157,7 +155,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex { anyStillPulling = true; - double factor = pullStrength / dist; + // Clamp speed to never exceed half the remaining distance, preventing overshoot/slingshot + double maxSpeed = dist * 0.5; + double effectiveSpeed = Math.min(pullStrength, maxSpeed); + double factor = effectiveSpeed / dist; double nextX = dx * factor; double nextY = dy * factor * 0.5; double nextZ = dz * factor; @@ -309,4 +310,31 @@ public class AbilityVortex extends Ability implements IAbilityVortex { public void setPullDamage(float pullDamage) { this.pullDamage = pullDamage; } + + @SideOnly(Side.CLIENT) + @Override + public void getAbilityDefinitions(List defs) { + defs.addAll(Arrays.asList( + FieldDef.row( + FieldDef.floatField("ability.pullRadius", this::getPullRadius, this::setPullRadius), + FieldDef.floatField("ability.pullStrength", this::getPullStrength, this::setPullStrength) + ), + FieldDef.section("ability.section.damage"), + FieldDef.row( + FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), + FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) + ), + FieldDef.section("ability.section.aoe"), + FieldDef.boolField("gui.enabled", this::isAoe, this::setAoe) + .hover("ability.hover.aoe"), + FieldDef.intField("ability.maxTargets", this::getMaxTargets, this::setMaxTargets) + .visibleWhen(this::isAoe), + FieldDef.section("ability.section.pullDamage"), + FieldDef.boolField("gui.enabled", this::isDamageOnPull, this::setDamageOnPull) + .hover("ability.hover.dmgOnPull"), + FieldDef.floatField("enchantment.damage", this::getPullDamage, this::setPullDamage) + .visibleWhen(this::isDamageOnPull), + AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) + )); + } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java index a9cfffc43..1427b298f 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityBeam.java @@ -1,6 +1,5 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; @@ -27,12 +26,6 @@ import java.util.List; */ public class EntityAbilityBeam extends EntityAbilityProjectile { - // Beam-specific movement properties - private float speed = 0.5f; - private boolean homing = true; - private float homingStrength = 0.35f; // Increased from 0.15 for better tracking - private float homingRange = 20.0f; - // Beam shape properties private float beamWidth = 0.3f; private float headSize = 0.5f; @@ -57,7 +50,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { private int chargeDuration = 40; private int chargeTick = 0; private float chargeOffsetDistance = 1.0f; - private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); // Trail fading for non-anchored beams (comet effect) private boolean fadeTrail = false; @@ -108,22 +100,20 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { * If false, beam is free-moving with trailing length (no tail orb). */ public EntityAbilityBeam(World world, EntityLivingBase owner, EntityLivingBase target, - double x, double y, double z, - float beamWidth, float headSize, - EnergyColorData color, EnergyCombatData combat, - EnergyHomingData homing, EnergyLightningData lightning, - EnergyLifespanData lifespan, - boolean anchoredMode) { + double x, double y, double z, + float beamWidth, float headSize, + EnergyDisplayData display, EnergyCombatData combat, + EnergyHomingData homing, EnergyLightningData lightning, + EnergyLifespanData lifespan, EnergyTrajectoryData trajectory, + boolean anchoredMode) { super(world); // Initialize base properties via parent - initProjectile(owner, target, x, y, z, headSize, color, combat, lightning, lifespan); + initProjectile(owner, target, x, y, z, headSize, display, combat, lightning, lifespan, trajectory); // Beam-specific properties from homing data - this.speed = homing.speed; - this.homing = homing.homing; - this.homingStrength = homing.homingStrength; - this.homingRange = homing.homingRange; + + this.homingData = homing; this.beamWidth = beamWidth; this.headSize = headSize; @@ -153,16 +143,16 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { double dz = target.posZ - z; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); if (len > 0) { - this.motionX = (dx / len) * speed; - this.motionY = (dy / len) * speed; - this.motionZ = (dz / len) * speed; + this.motionX = (dx / len) * getSpeed(); + this.motionY = (dy / len) * getSpeed(); + this.motionZ = (dz / len) * getSpeed(); } } else { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - this.motionY = -Math.sin(pitch) * speed; - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + this.motionY = -Math.sin(pitch) * getSpeed(); + this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); } } @@ -178,7 +168,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { this.motionZ = 0; } - public void setupPreview(EntityLivingBase owner, float beamWidth, float headSize, EnergyColorData color, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) { + public void setupPreview(EntityLivingBase owner, float beamWidth, float headSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, float chargeOffsetDistance) { this.setPreviewMode(true); this.setPreviewOwner(owner); @@ -186,15 +176,8 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { this.beamWidth = beamWidth; this.headSize = headSize; this.size = headSize; - this.innerColor = color.innerColor; - this.outerColor = color.outerColor; - this.outerColorEnabled = color.outerColorEnabled; - this.outerColorWidth = color.outerColorWidth; - this.outerColorAlpha = color.outerColorAlpha; - this.rotationSpeed = color.rotationSpeed; - this.lightningEffect = lightning.lightningEffect; - this.lightningDensity = lightning.lightningDensity; - this.lightningRadius = lightning.lightningRadius; + this.displayData = display; + this.lightningData = lightning; // Set charging state this.setCharging(true); @@ -239,26 +222,41 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { setCharging(false); - // Update start position to current position + // Origin (tail) stays at the charged position startX = posX; startY = posY; startZ = posZ; + // Reset head offset to origin + headOffsetX = 0; + headOffsetY = 0; + headOffsetZ = 0; + prevHeadOffsetX = 0; + prevHeadOffsetY = 0; + prevHeadOffsetZ = 0; + + // Origin no longer follows owner after firing + attachedToOwner = false; + // Sync prev position to prevent visual jump on first frame prevPosX = posX; prevPosY = posY; prevPosZ = posZ; + // Reset trail + trailPoints.clear(); + trailPointAges.clear(); + trailPoints.add(Vec3.createVectorHelper(0, 0, 0)); + // Fire forward based on owner facing direction - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); - float pitch = 0; // Fire horizontally - motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - motionY = -Math.sin(pitch) * speed; - motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + motionX = -Math.sin(yaw) * getSpeed(); + motionY = 0; + motionZ = Math.cos(yaw) * getSpeed(); } else { - motionX = speed; + motionX = getSpeed(); motionY = 0; motionZ = 0; } @@ -301,7 +299,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { if (fadeTrail) trailPointAges.add(0); // Calculate velocity toward target (head starts at origin = startX/Y/Z) - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (target != null) { double dx = target.posX - startX; @@ -309,16 +307,16 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { double dz = target.posZ - startZ; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); if (len > 0) { - motionX = (dx / len) * speed; - motionY = (dy / len) * speed; - motionZ = (dz / len) * speed; + motionX = (dx / len) * getSpeed(); + motionY = (dy / len) * getSpeed(); + motionZ = (dz / len) * getSpeed(); } } else if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(owner.rotationPitch); - motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - motionY = -Math.sin(pitch) * speed; - motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + motionY = -Math.sin(pitch) * getSpeed(); + motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); } if (DEBUG_LOGGING && !worldObj.isRemote) { @@ -336,9 +334,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { headOffsetY * headOffsetY + headOffsetZ * headOffsetZ ); - boolean exceeded = distFromOrigin >= maxDistance; + boolean exceeded = distFromOrigin >= getMaxDistance(); if (exceeded && !worldObj.isRemote && DEBUG_LOGGING) { - LogWriter.info("[Beam] DEAD: Max distance exceeded. dist=" + distFromOrigin + " max=" + maxDistance); + LogWriter.info("[Beam] DEAD: Max distance exceeded. dist=" + distFromOrigin + " max=" + getMaxDistance()); } return exceeded; } @@ -392,7 +390,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Update origin if attached to owner if (attachedToOwner) { - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner != null) { startX = owner.posX; startY = owner.posY + owner.getEyeHeight() * 0.7; @@ -436,7 +434,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { private void updateCharging() { chargeTick++; - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner == null || owner.isDead) { setDead(); return; @@ -458,13 +456,11 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { ); } - // Offset downward by half headSize to center - double centeredY = pos.yCoord - headSize * 0.5; - setPosition(pos.xCoord, centeredY, pos.zCoord); + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); // Also update origin for when firing starts startX = pos.xCoord; - startY = centeredY; + startY = pos.yCoord; startZ = pos.zCoord; } @@ -529,7 +525,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { // Update origin if attached to owner if (attachedToOwner) { - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner != null) { startX = owner.posX; startY = owner.posY + owner.getEyeHeight() * 0.7; @@ -550,9 +546,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { } private void updateHoming() { - if (!homing) return; + if (!isHoming()) return; - Entity target = getTarget(); + Entity target = getTargetEntity(); if (target == null || !target.isEntityAlive()) return; // Calculate world position of head @@ -565,18 +561,18 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { double dz = target.posZ - headWorldZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist <= homingRange && dist > 0) { + if (dist <= getHomingRange() && dist > 0) { // Calculate effective homing strength - increases when closer to commit to target - float effectiveStrength = homingStrength; - if (dist < homingRange * 0.3) { - effectiveStrength = Math.min(1.0f, homingStrength * 2.5f); - } else if (dist < homingRange * 0.6) { - effectiveStrength = Math.min(0.8f, homingStrength * 1.5f); + float effectiveStrength = getHomingStrength(); + if (dist < getHomingRange() * 0.3) { + effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); + } else if (dist < getHomingRange() * 0.6) { + effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); } - double desiredVX = (dx / dist) * speed; - double desiredVY = (dy / dist) * speed; - double desiredVZ = (dz / dist) * speed; + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); motionX += (desiredVX - motionX) * effectiveStrength; motionY += (desiredVY - motionY) * effectiveStrength; @@ -584,9 +580,9 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); if (vLen > 0) { - motionX = (motionX / vLen) * speed; - motionY = (motionY / vLen) * speed; - motionZ = (motionZ / vLen) * speed; + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); } } } @@ -604,7 +600,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { hasHit = true; - if (explosive) { + if (isExplosive()) { posX = blockHit.hitVec.xCoord; posY = blockHit.hitVec.yCoord; posZ = blockHit.hitVec.zCoord; @@ -632,7 +628,7 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { } hasHit = true; - if (explosive) { + if (isExplosive()) { posX = headX; posY = headY; posZ = headZ; @@ -748,10 +744,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { @Override protected void readProjectileNBT(NBTTagCompound nbt) { - this.speed = nbt.hasKey("Speed") ? nbt.getFloat("Speed") : 0.5f; - this.homing = !nbt.hasKey("Homing") || nbt.getBoolean("Homing"); - this.homingStrength = nbt.hasKey("HomingStrength") ? nbt.getFloat("HomingStrength") : 0.15f; - this.homingRange = nbt.hasKey("HomingRange") ? nbt.getFloat("HomingRange") : 20.0f; this.beamWidth = nbt.hasKey("BeamWidth") ? nbt.getFloat("BeamWidth") : 0.3f; this.headSize = nbt.hasKey("HeadSize") ? nbt.getFloat("HeadSize") : 0.5f; this.headOffsetX = nbt.hasKey("HeadOffsetX") ? nbt.getDouble("HeadOffsetX") : 0; @@ -772,7 +764,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { this.fadeTrail = nbt.hasKey("FadeTrail") && nbt.getBoolean("FadeTrail"); this.trailFadeTime = nbt.hasKey("TrailFadeTime") ? nbt.getInteger("TrailFadeTime") : 20; - this.anchorData.readNBT(nbt); // Read trail points (relative to origin) trailPoints.clear(); @@ -791,10 +782,6 @@ public class EntityAbilityBeam extends EntityAbilityProjectile { @Override protected void writeProjectileNBT(NBTTagCompound nbt) { - nbt.setFloat("Speed", speed); - nbt.setBoolean("Homing", homing); - nbt.setFloat("HomingStrength", homingStrength); - nbt.setFloat("HomingRange", homingRange); nbt.setFloat("BeamWidth", beamWidth); nbt.setFloat("HeadSize", headSize); nbt.setDouble("HeadOffsetX", headOffsetX); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java index 7dc3a8a82..edd7b3dff 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityDisc.java @@ -1,6 +1,5 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; @@ -21,11 +20,7 @@ import java.util.List; */ public class EntityAbilityDisc extends EntityAbilityProjectile { - // Disc-specific movement properties - private float speed = 0.5f; - private boolean homing = true; - private float homingStrength = 0.35f; // Increased from 0.15 for better tracking - private float homingRange = 20.0f; + // Disc-specific movement propertie // Boomerang properties private boolean boomerang = false; @@ -36,6 +31,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { // Disc shape properties private float discRadius = 1.0f; // Width of disc private float discThickness = 0.2f; // Height of disc + private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward) // Charging state (during windup) private boolean charging = false; @@ -43,7 +39,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { private int chargeTick = 0; private float targetDiscRadius = 1.0f; // Full radius to grow to during charging private float targetDiscThickness = 0.2f; // Full thickness to grow to during charging - private EnergyAnchorData anchorData = new EnergyAnchorData(); // Data watcher index for charging state (synced to clients) private static final int DW_CHARGING = 20; @@ -84,22 +79,18 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Full constructor with all parameters using data classes. */ public EntityAbilityDisc(World world, EntityLivingBase owner, EntityLivingBase target, - double x, double y, double z, - float discRadius, float discThickness, - EnergyColorData color, EnergyCombatData combat, - EnergyHomingData homing, EnergyLightningData lightning, - EnergyLifespanData lifespan, - boolean boomerang, int boomerangDelay) { + double x, double y, double z, + float discRadius, float discThickness, + EnergyDisplayData display, EnergyCombatData combat, + EnergyHomingData homing, EnergyLightningData lightning, + EnergyLifespanData lifespan, EnergyTrajectoryData trajectory, + boolean boomerang, int boomerangDelay) { super(world); // Initialize base properties - initProjectile(owner, target, x, y, z, discRadius, color, combat, lightning, lifespan); + initProjectile(owner, target, x, y, z, discRadius, display, combat, lightning, lifespan, trajectory); - // Disc-specific properties from homing data - this.speed = homing.speed; - this.homing = homing.homing; - this.homingStrength = homing.homingStrength; - this.homingRange = homing.homingRange; + this.homingData = homing; this.boomerang = boomerang; this.boomerangDelay = boomerangDelay; @@ -114,16 +105,16 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { double dz = target.posZ - z; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); if (len > 0) { - this.motionX = (dx / len) * speed; - this.motionY = (dy / len) * speed; - this.motionZ = (dz / len) * speed; + this.motionX = (dx / len) * getSpeed(); + this.motionY = (dy / len) * getSpeed(); + this.motionZ = (dz / len) * getSpeed(); } } else { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(owner.rotationPitch); - this.motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - this.motionY = -Math.sin(pitch) * speed; - this.motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + this.motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + this.motionY = -Math.sin(pitch) * getSpeed(); + this.motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); } } @@ -132,11 +123,12 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * The disc will grow from 0 to discRadius over chargeDuration ticks. * Position follows the owner based on anchor point. */ - public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { + public void setupCharging(EnergyAnchorData anchor, int chargeDuration, boolean vertical) { setCharging(true); this.chargeDuration = chargeDuration; this.chargeTick = 0; this.anchorData = anchor; + this.vertical = vertical; this.targetDiscRadius = this.discRadius; this.targetDiscThickness = this.discThickness; this.discRadius = 0.01f; @@ -154,25 +146,20 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { * Follows anchor point and animations like in the real game. * Can be fired when transitioning to active phase. */ - public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyColorData color, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) { + public void setupPreview(EntityLivingBase owner, float discRadius, float discThickness, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration, boolean vertical) { this.setPreviewMode(true); this.setPreviewOwner(owner); // Set visual properties - this.innerColor = color.innerColor; - this.outerColor = color.outerColor; - this.outerColorEnabled = color.outerColorEnabled; - this.outerColorWidth = color.outerColorWidth; - this.rotationSpeed = color.rotationSpeed; - this.lightningEffect = lightning.lightningEffect; - this.lightningDensity = lightning.lightningDensity; - this.lightningRadius = lightning.lightningRadius; + this.displayData = display; + this.lightningData = lightning; // Set charging state this.setCharging(true); this.chargeDuration = chargeDuration; this.chargeTick = 0; this.anchorData = anchor; + this.vertical = vertical; // Store target size and start at 0 for grow effect this.targetDiscRadius = discRadius; @@ -216,15 +203,15 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { prevPosZ = posZ; // Fire forward based on owner facing direction - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = 0; // Fire horizontally - motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - motionY = -Math.sin(pitch) * speed; - motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + motionY = -Math.sin(pitch) * getSpeed(); + motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); } else { - motionX = speed; + motionX = getSpeed(); motionY = 0; motionZ = 0; } @@ -245,7 +232,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { startZ = posZ; // Calculate velocity toward target - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (target != null) { double dx = target.posX - posX; @@ -253,23 +240,23 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { double dz = target.posZ - posZ; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); if (len > 0) { - motionX = (dx / len) * speed; - motionY = (dy / len) * speed; - motionZ = (dz / len) * speed; + motionX = (dx / len) * getSpeed(); + motionY = (dy / len) * getSpeed(); + motionZ = (dz / len) * getSpeed(); } } else if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(owner.rotationPitch); - motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - motionY = -Math.sin(pitch) * speed; - motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + motionY = -Math.sin(pitch) * getSpeed(); + motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); } } @Override protected void updateRotation() { // Disc spins ONLY on Y axis (flat spin like a saw blade) - this.rotationValY += rotationSpeed; + this.rotationValY += getRotationSpeed(); // No wobble - keep X and Z at 0 for stable flight if (this.rotationValY > 360.0f) this.rotationValY -= 360.0f; } @@ -312,7 +299,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { if (this.isCollidedHorizontally || this.isCollidedVertically) { if (!worldObj.isRemote) { hasHit = true; - if (explosive) { + if (isExplosive()) { doExplosion(); } } @@ -331,14 +318,14 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { if (boomerang) { // If not returning yet, check if we should start returning if (!returning && !hasHit) { - if (distTraveled >= maxDistance * 0.8 || ticksSinceMiss >= boomerangDelay) { + if (distTraveled >= getMaxDistance() * 0.8 || ticksSinceMiss >= boomerangDelay) { returning = true; } } // If returning, only die when close to owner if (returning) { - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner != null) { double distToOwner = Math.sqrt( (posX - owner.posX) * (posX - owner.posX) + @@ -356,7 +343,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { } // Non-boomerang: standard max distance check - return distTraveled >= maxDistance; + return distTraveled >= getMaxDistance(); } /** @@ -370,9 +357,9 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { } private void updateHoming() { - if (!homing) return; + if (!isHoming()) return; - Entity target = getTarget(); + Entity target = getTargetEntity(); if (target == null || !target.isEntityAlive()) return; double dx = target.posX - posX; @@ -380,18 +367,18 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { double dz = target.posZ - posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist <= homingRange && dist > 0) { + if (dist <= getHomingRange() && dist > 0) { // Calculate effective homing strength - increases when closer to commit to target - float effectiveStrength = homingStrength; - if (dist < homingRange * 0.3) { - effectiveStrength = Math.min(1.0f, homingStrength * 2.5f); - } else if (dist < homingRange * 0.6) { - effectiveStrength = Math.min(0.8f, homingStrength * 1.5f); + float effectiveStrength = getHomingStrength(); + if (dist < getHomingRange() * 0.3) { + effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); + } else if (dist < getHomingRange() * 0.6) { + effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); } - double desiredVX = (dx / dist) * speed; - double desiredVY = (dy / dist) * speed; - double desiredVZ = (dz / dist) * speed; + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); motionX += (desiredVX - motionX) * effectiveStrength; motionY += (desiredVY - motionY) * effectiveStrength; @@ -399,15 +386,15 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); if (vLen > 0) { - motionX = (motionX / vLen) * speed; - motionY = (motionY / vLen) * speed; - motionZ = (motionZ / vLen) * speed; + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); } } } private void updateReturnToOwner() { - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); // If owner is gone (unloaded/dead), head back toward start position double targetX, targetY, targetZ; @@ -429,10 +416,10 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { if (dist > 0) { // Stronger homing when returning - double returnStrength = Math.min(1.0, homingStrength * 2.5); - double desiredVX = (dx / dist) * speed; - double desiredVY = (dy / dist) * speed; - double desiredVZ = (dz / dist) * speed; + double returnStrength = Math.min(1.0, getHomingStrength() * 2.5); + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); motionX += (desiredVX - motionX) * returnStrength; motionY += (desiredVY - motionY) * returnStrength; @@ -440,9 +427,9 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); if (vLen > 0) { - motionX = (motionX / vLen) * speed; - motionY = (motionY / vLen) * speed; - motionZ = (motionZ / vLen) * speed; + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); } } } @@ -455,7 +442,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { hasHit = true; - if (explosive) { + if (isExplosive()) { posX = blockHit.hitVec.xCoord; posY = blockHit.hitVec.yCoord; posZ = blockHit.hitVec.zCoord; @@ -482,7 +469,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { hasHit = true; - if (explosive) { + if (isExplosive()) { doExplosion(); } else { applyDamage(entity); @@ -499,7 +486,7 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { private void updateCharging() { chargeTick++; - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner == null || owner.isDead) { setDead(); return; @@ -541,14 +528,6 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { // ==================== GETTERS ==================== - public float getSpeed() { - return speed; - } - - public boolean isHoming() { - return homing; - } - public float getDiscRadius() { return discRadius; } @@ -565,18 +544,37 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { return returning; } + public boolean isVertical() { + return vertical; + } + + /** + * Get the yaw angle (degrees) from motion vector for vertical disc orientation. + * During charging, uses owner's facing direction. + */ + public float getTravelYaw() { + if (isCharging()) { + Entity owner = previewMode ? previewOwner : getOwnerEntity(); + if (owner != null) { + return owner.rotationYaw; + } + } + double speed = Math.sqrt(motionX * motionX + motionZ * motionZ); + if (speed > 0.001) { + return (float) (Math.atan2(-motionX, motionZ) * 180.0 / Math.PI); + } + return 0.0f; + } + // ==================== NBT ==================== @Override protected void readProjectileNBT(NBTTagCompound nbt) { - this.speed = nbt.hasKey("Speed") ? nbt.getFloat("Speed") : 0.5f; - this.homing = !nbt.hasKey("Homing") || nbt.getBoolean("Homing"); - this.homingStrength = nbt.hasKey("HomingStrength") ? nbt.getFloat("HomingStrength") : 0.15f; - this.homingRange = nbt.hasKey("HomingRange") ? nbt.getFloat("HomingRange") : 20.0f; this.boomerang = nbt.hasKey("Boomerang") && nbt.getBoolean("Boomerang"); this.boomerangDelay = nbt.hasKey("BoomerangDelay") ? nbt.getInteger("BoomerangDelay") : 40; this.discRadius = nbt.hasKey("DiscRadius") ? nbt.getFloat("DiscRadius") : 1.0f; this.discThickness = nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f; + this.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false; this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning"); // Charging state boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); @@ -586,19 +584,15 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; this.targetDiscRadius = nbt.hasKey("TargetDiscRadius") ? nbt.getFloat("TargetDiscRadius") : this.discRadius; this.targetDiscThickness = nbt.hasKey("TargetDiscThickness") ? nbt.getFloat("TargetDiscThickness") : this.discThickness; - this.anchorData.readNBT(nbt); } @Override protected void writeProjectileNBT(NBTTagCompound nbt) { - nbt.setFloat("Speed", speed); - nbt.setBoolean("Homing", homing); - nbt.setFloat("HomingStrength", homingStrength); - nbt.setFloat("HomingRange", homingRange); nbt.setBoolean("Boomerang", boomerang); nbt.setInteger("BoomerangDelay", boomerangDelay); nbt.setFloat("DiscRadius", discRadius); nbt.setFloat("DiscThickness", discThickness); + nbt.setBoolean("Vertical", vertical); nbt.setBoolean("Returning", returning); // Charging state nbt.setBoolean("Charging", isCharging()); @@ -606,8 +600,5 @@ public class EntityAbilityDisc extends EntityAbilityProjectile { nbt.setInteger("ChargeTick", chargeTick); nbt.setFloat("TargetDiscRadius", targetDiscRadius); nbt.setFloat("TargetDiscThickness", targetDiscThickness); - - // Anchor data - this.anchorData.writeNBT(nbt); } } diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java index 3d888c698..8a1325a27 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityLaser.java @@ -1,9 +1,7 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.data.EnergyColorData; -import kamkeel.npcs.controllers.data.ability.data.EnergyCombatData; -import kamkeel.npcs.controllers.data.ability.data.EnergyLifespanData; -import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; +import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; @@ -37,30 +35,70 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { // Direction (normalized) private double dirX, dirY, dirZ; + // Lock vertical direction after firing (only update yaw, keep pitch fixed) + private boolean lockVerticalDirection = false; + // Track hit entities to avoid double-damage private Set hitEntities = new HashSet<>(); // End point for rendering private double endX, endY, endZ; + // Charging state (during windup) + private boolean charging = false; + private int chargeDuration = 40; + private int chargeTick = 0; + private float targetSize = 1.0f; // Full size to grow to during charging + + // Data watcher index for charging state (synced to clients) + private static final int DW_CHARGING = 20; + public EntityAbilityLaser(World world) { super(world); } + @Override + protected void entityInit() { + super.entityInit(); + // Register data watcher for charging state + this.dataWatcher.addObject(DW_CHARGING, (byte) 0); + } + + /** + * Check if orb is in charging state (synced via data watcher). + * In preview mode, uses local field since data watcher isn't synced. + */ + public boolean isCharging() { + if (previewMode) { + return this.charging; + } + return this.dataWatcher.getWatchableObjectByte(DW_CHARGING) == 1; + } + + /** + * Set charging state (server only, synced to clients via data watcher). + */ + private void setCharging(boolean value) { + this.charging = value; + if (!worldObj.isRemote) { + this.dataWatcher.updateObject(DW_CHARGING, (byte) (value ? 1 : 0)); + } + } + /** * Full constructor with all parameters using data classes. */ public EntityAbilityLaser(World world, EntityLivingBase owner, EntityLivingBase target, - double x, double y, double z, - float laserWidth, - EnergyColorData color, EnergyCombatData combat, - EnergyLightningData lightning, EnergyLifespanData lifespan, - float expansionSpeed, int lingerTicks) { + double x, double y, double z, + float laserWidth, + EnergyDisplayData display, EnergyCombatData combat, + EnergyLightningData lightning, EnergyLifespanData lifespan, + EnergyTrajectoryData trajectory, float expansionSpeed, int lingerTicks) { super(world); // Initialize base properties (laser doesn't rotate) - initProjectile(owner, target, x, y, z, laserWidth, color, combat, lightning, lifespan); - this.rotationSpeed = 0.0f; + initProjectile(owner, target, x, y, z, laserWidth, display, combat, lightning, lifespan, trajectory); + this.displayData.rotationSpeed = 0.0f; // Laser-specific properties this.laserWidth = laserWidth; @@ -70,7 +108,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { // Calculate direction toward target or forward if (target != null) { double dx = target.posX - x; - double dy = (target.posY + target.getEyeHeight()) - y; + double dy = (target.posY + target.getEyeHeight() - 0.4) - y; double dz = target.posZ - z; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); if (len > 0) { @@ -93,6 +131,25 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.endZ = z; } + /** + * Setup this orb in charging mode (for windup phase). + * The orb will grow from 0 to orbSize over chargeDuration ticks. + * Position follows the owner based on anchor point. + */ + public void setupCharging(EnergyAnchorData anchor, int chargeDuration) { + setCharging(true); + this.chargeDuration = chargeDuration; + this.chargeTick = 0; + this.anchorData = anchor; + this.targetSize = this.size; + this.size = 0.01f; + this.renderCurrentSize = 0.01f; + this.prevRenderSize = 0.01f; + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + } + @Override protected void updateRotation() { // Laser doesn't rotate @@ -106,12 +163,21 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { @Override protected void updateProjectile() { + if (isCharging()) { + updateCharging(); + return; + } + + // Track owner's anchor position and rotation each tick + // so the laser follows the NPC's facing direction + updateLaserOriginAndDirection(); + if (!fullyExtended) { // Expand the laser currentLength += expansionSpeed; - if (currentLength >= maxDistance) { - currentLength = maxDistance; + if (currentLength >= getMaxDistance()) { + currentLength = getMaxDistance(); fullyExtended = true; } @@ -128,12 +194,100 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } else { // Laser is fully extended, count down linger time ticksSinceFullExtension++; + + // Update end point during linger (origin/direction may still change) + endX = startX + dirX * currentLength; + endY = startY + dirY * currentLength; + endZ = startZ + dirZ * currentLength; + if (ticksSinceFullExtension >= lingerTicks) { this.setDead(); } } } + /** + * Update laser origin and direction from the owner's current anchor position and rotation. + * Called each tick so the laser follows the NPC when tracking a target. + */ + private void updateLaserOriginAndDirection() { + Entity owner = getOwnerEntity(); + if (owner == null || owner.isDead) return; + if (!(owner instanceof EntityLivingBase)) return; + + EntityLivingBase livingOwner = (EntityLivingBase) owner; + + // Update origin from anchor point + if (anchorData != null) { + Vec3 pos = AnchorPointHelper.calculateAnchorPosition(livingOwner, anchorData); + startX = pos.xCoord; + startY = pos.yCoord; + startZ = pos.zCoord; + } else { + startX = owner.posX; + startY = owner.posY + owner.height * 0.7; + startZ = owner.posZ; + } + + // Update direction from owner's current rotation + float yaw = (float) Math.toRadians(owner.rotationYaw); + if (lockVerticalDirection) { + // Only update horizontal direction (yaw), keep vertical (pitch) fixed + double horizontalLen = Math.sqrt(dirX * dirX + dirZ * dirZ); + if (horizontalLen < 0.001) horizontalLen = 1.0; + dirX = -Math.sin(yaw) * horizontalLen; + dirZ = Math.cos(yaw) * horizontalLen; + } else { + float pitch = (float) Math.toRadians(owner.rotationPitch); + dirX = -Math.sin(yaw) * Math.cos(pitch); + dirY = -Math.sin(pitch); + dirZ = Math.cos(yaw) * Math.cos(pitch); + } + + // Keep entity positioned at origin + prevPosX = startX; + prevPosY = startY; + prevPosZ = startZ; + setPosition(startX, startY, startZ); + } + + public void startMoving(EntityLivingBase target) { + if (!isCharging()) return; + + setCharging(false); + + // Initialize from current anchor position + // updateLaserOriginAndDirection() will keep these updated each tick + startX = posX; + startY = posY; + startZ = posZ; + + // Set initial direction from owner's rotation + Entity owner = getOwnerEntity(); + if (owner != null) { + float yaw = (float) Math.toRadians(owner.rotationYaw); + float pitch = (float) Math.toRadians(owner.rotationPitch); + this.dirX = -Math.sin(yaw) * Math.cos(pitch); + this.dirY = -Math.sin(pitch); + this.dirZ = Math.cos(yaw) * Math.cos(pitch); + } else if (target != null) { + double dx = target.posX - startX; + double dy = (target.posY + target.getEyeHeight() - 0.4) - startY; + double dz = target.posZ - startZ; + double len = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (len > 0) { + this.dirX = dx / len; + this.dirY = dy / len; + this.dirZ = dz / len; + } + } + + // Initialize end point at start (will expand from here) + this.endX = startX; + this.endY = startY; + this.endZ = startZ; + } + private void checkBlockCollision() { Vec3 start = Vec3.createVectorHelper(startX, startY, startZ); Vec3 end = Vec3.createVectorHelper(endX, endY, endZ); @@ -152,7 +306,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { endZ = blockHit.hitVec.zCoord; fullyExtended = true; - if (explosive) { + if (isExplosive()) { // Explode at hit point double oldPosX = posX; double oldPosY = posY; @@ -168,15 +322,53 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } } + /** + * Update during charging state - follow owner based on anchor point. + */ + private void updateCharging() { + chargeTick++; + + Entity owner = getOwnerEntity(); + if (owner == null || owner.isDead) { + setDead(); + return; + } + + // Grow size based on charge progress + float progress = getChargeProgress(); + this.size = targetSize * progress; + + // Calculate position based on anchor point, offset downward by half size to center + if (owner instanceof EntityLivingBase) { + Vec3 pos = AnchorPointHelper.calculateAnchorPosition((EntityLivingBase) owner, anchorData); + setPosition(pos.xCoord, pos.yCoord, pos.zCoord); + } + } + + /** + * Get the charge progress (0-1). + */ + public float getChargeProgress() { + if (chargeDuration <= 0) return 1.0f; + return Math.min(1.0f, (float) chargeTick / chargeDuration); + } + + public float getInterpolatedChargeProgress(float partialTicks) { + if (chargeDuration <= 0) return 1.0f; + float prevProgress = Math.max(0, (float) (chargeTick - 1) / chargeDuration); + float currProgress = Math.min(1.0f, (float) chargeTick / chargeDuration); + return prevProgress + (currProgress - prevProgress) * partialTicks; + } + private void checkEntityCollisionAlongLine() { - // Check collision along the entire laser line - // Use a slightly expanded AABB for the full line - double minX = Math.min(startX, endX) - laserWidth; - double minY = Math.min(startY, endY) - laserWidth; - double minZ = Math.min(startZ, endZ) - laserWidth; - double maxX = Math.max(startX, endX) + laserWidth; - double maxY = Math.max(startY, endY) + laserWidth; - double maxZ = Math.max(startZ, endZ) + laserWidth; + // Expand search AABB by entity sizes to ensure we find all potential targets + double expand = Math.max(laserWidth, 1.0); + double minX = Math.min(startX, endX) - expand; + double minY = Math.min(startY, endY) - expand; + double minZ = Math.min(startZ, endZ) - expand; + double maxX = Math.max(startX, endX) + expand; + double maxY = Math.max(startY, endY) + expand; + double maxZ = Math.max(startZ, endZ) + expand; AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); @@ -187,7 +379,7 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { if (shouldIgnoreEntity(entity)) continue; if (hitEntities.contains(entity.getEntityId())) continue; - // Check if entity is close to the laser line + // Check if entity's bounding box intersects with the laser line if (isEntityOnLine(entity)) { hitEntities.add(entity.getEntityId()); applyDamage(entity); @@ -198,42 +390,64 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { } /** - * Check if an entity intersects with the laser line. + * Check if an entity's bounding box intersects with the laser line. + * Uses separate XZ (horizontal) and Y (vertical) checks against + * the entity's full bounding box rather than just its center point. */ private boolean isEntityOnLine(EntityLivingBase entity) { - // Get entity center double ex = entity.posX; - double ey = entity.posY + entity.height * 0.5; double ez = entity.posZ; - // Vector from start to entity + // Project entity XZ position onto the laser line direction double vx = ex - startX; - double vy = ey - startY; double vz = ez - startZ; - - // Project onto line direction - double dot = vx * dirX + vy * dirY + vz * dirZ; - - // Clamp to line segment + // Project using horizontal direction components only + double dirLenXZ = Math.sqrt(dirX * dirX + dirZ * dirZ); + double dot; + if (dirLenXZ > 0.001) { + dot = (vx * dirX + vz * dirZ) / (dirLenXZ * dirLenXZ) * dirLenXZ; + // Remap to full 3D parameter + dot = (vx * dirX + vz * dirZ + (entity.posY + entity.height * 0.5 - startY) * dirY); + } else { + // Laser fires nearly straight up/down - use full 3D projection + dot = vx * dirX + (entity.posY + entity.height * 0.5 - startY) * dirY + vz * dirZ; + } dot = Math.max(0, Math.min(dot, currentLength)); - // Closest point on line + // Closest point on laser line at this parameter double closestX = startX + dirX * dot; double closestY = startY + dirY * dot; double closestZ = startZ + dirZ * dot; - // Distance from entity to closest point - double distSq = (ex - closestX) * (ex - closestX) + - (ey - closestY) * (ey - closestY) + - (ez - closestZ) * (ez - closestZ); + // XZ distance check: entity center vs laser line point + // Use minimum collision width so visually thin lasers still hit reliably + double xzDistSq = (ex - closestX) * (ex - closestX) + (ez - closestZ) * (ez - closestZ); + double effectiveWidth = Math.max(laserWidth, 0.5); + double hitRadiusXZ = effectiveWidth * 0.5 + entity.width * 0.5; + if (xzDistSq > hitRadiusXZ * hitRadiusXZ) return false; - // Hit if within laser width + entity radius - double hitRadius = laserWidth * 0.5 + entity.width * 0.5; - return distSq <= hitRadius * hitRadius; + // Y overlap check: laser point vs entity's full height range + double entityMinY = entity.boundingBox.minY; + double entityMaxY = entity.boundingBox.maxY; + double laserHalfWidth = effectiveWidth * 0.5; + + // Check if laser Y is within entity's height range (expanded by laser half-width) + if (closestY < entityMinY - laserHalfWidth) return false; + if (closestY > entityMaxY + laserHalfWidth) return false; + + return true; } // ==================== GETTERS FOR RENDERER ==================== + public void setLockVerticalDirection(boolean lock) { + this.lockVerticalDirection = lock; + } + + public boolean isLockVerticalDirection() { + return lockVerticalDirection; + } + public float getLaserWidth() { return laserWidth; } @@ -305,6 +519,14 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { this.endX = nbt.getDouble("EndX"); this.endY = nbt.getDouble("EndY"); this.endZ = nbt.getDouble("EndZ"); + + // Charging state + boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); + this.charging = isCharging; + this.dataWatcher.updateObject(DW_CHARGING, (byte) (isCharging ? 1 : 0)); + this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; + this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; + this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; } @Override @@ -320,13 +542,19 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { nbt.setDouble("EndX", endX); nbt.setDouble("EndY", endY); nbt.setDouble("EndZ", endZ); + + // Charging state + nbt.setBoolean("Charging", isCharging()); + nbt.setInteger("ChargeDuration", chargeDuration); + nbt.setInteger("ChargeTick", chargeTick); + nbt.setFloat("TargetSize", targetSize); } /** * Setup this laser in preview mode for GUI display. * Laser doesn't have charging state - spawns at active phase and fires immediately. */ - public void setupPreview(EntityLivingBase owner, float laserWidth, EnergyColorData color, + public void setupPreview(EntityLivingBase owner, float laserWidth, EnergyDisplayData display, EnergyLightningData lightning, float expansionSpeed, float maxDistance) { this.setPreviewMode(true); this.setPreviewOwner(owner); @@ -334,15 +562,10 @@ public class EntityAbilityLaser extends EntityAbilityProjectile { // Set visual properties this.laserWidth = laserWidth; this.size = laserWidth; - this.innerColor = color.innerColor; - this.outerColor = color.outerColor; - this.outerColorEnabled = color.outerColorEnabled; - this.outerColorWidth = color.outerColorWidth; + this.displayData = display; this.expansionSpeed = expansionSpeed; - this.maxDistance = Math.min(maxDistance, 5.0f); // Limit for GUI preview - this.lightningEffect = lightning.lightningEffect; - this.lightningDensity = lightning.lightningDensity; - this.lightningRadius = lightning.lightningRadius; + this.lifespanData.maxDistance = Math.min(maxDistance, 5.0f); // Limit for GUI preview + this.lightningData = lightning; // Position at chest height double x = owner.posX; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java index c403f25de..73e8c26f3 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityOrb.java @@ -1,6 +1,5 @@ package kamkeel.npcs.entity; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; import kamkeel.npcs.controllers.data.ability.data.*; import kamkeel.npcs.util.AnchorPointHelper; import net.minecraft.entity.Entity; @@ -21,17 +20,10 @@ import java.util.List; */ public class EntityAbilityOrb extends EntityAbilityProjectile { - // Orb-specific movement properties - private float speed = 0.5f; - private boolean homing = true; - private float homingStrength = 0.35f; // Increased from 0.15 for better tracking - private float homingRange = 20.0f; - // Charging state (during windup) private boolean charging = false; private int chargeDuration = 40; private int chargeTick = 0; - private EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); private float targetSize = 1.0f; // Full size to grow to during charging // Data watcher index for charging state (synced to clients) @@ -74,19 +66,15 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { */ public EntityAbilityOrb(World world, EntityLivingBase owner, EntityLivingBase target, double x, double y, double z, float orbSize, - EnergyColorData color, EnergyCombatData combat, + EnergyDisplayData display, EnergyCombatData combat, EnergyHomingData homing, EnergyLightningData lightning, - EnergyLifespanData lifespan) { + EnergyLifespanData lifespan, EnergyTrajectoryData trajectory) { super(world); // Initialize base properties - initProjectile(owner, target, x, y, z, orbSize, color, combat, lightning, lifespan); + initProjectile(owner, target, x, y, z, orbSize, display, combat, lightning, lifespan, trajectory); - // Orb-specific properties - this.speed = homing.speed; - this.homing = homing.homing; - this.homingStrength = homing.homingStrength; - this.homingRange = homing.homingRange; + this.homingData = homing; // Calculate initial velocity toward target if (target != null) { @@ -133,20 +121,13 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { * Follows anchor point and animations like in the real game. * Can be fired when transitioning to active phase. */ - public void setupPreview(EntityLivingBase owner, float orbSize, EnergyColorData color, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) { + public void setupPreview(EntityLivingBase owner, float orbSize, EnergyDisplayData display, EnergyLightningData lightning, EnergyAnchorData anchor, int chargeDuration) { this.setPreviewMode(true); this.setPreviewOwner(owner); // Set visual properties - this.innerColor = color.innerColor; - this.outerColor = color.outerColor; - this.outerColorEnabled = color.outerColorEnabled; - this.outerColorWidth = color.outerColorWidth; - this.rotationSpeed = color.rotationSpeed; - this.lightningEffect = lightning.lightningEffect; - this.lightningDensity = lightning.lightningDensity; - this.lightningRadius = lightning.lightningRadius; - this.lightningFadeTime = lightning.lightningFadeTime; + this.displayData = display; + this.lightningData = lightning; // Set charging state this.setCharging(true); @@ -195,16 +176,16 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { prevPosZ = posZ; // Fire forward based on owner facing direction - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(0); // Fire horizontally - motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - motionY = -Math.sin(pitch) * speed; - motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + motionY = -Math.sin(pitch) * getSpeed(); + motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); } else { // Default: fire forward (positive X in model space) - motionX = speed; + motionX = getSpeed(); motionY = 0; motionZ = 0; } @@ -225,7 +206,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { startZ = posZ; // Calculate velocity toward target - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (target != null) { double dx = target.posX - posX; @@ -233,16 +214,16 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { double dz = target.posZ - posZ; double len = Math.sqrt(dx * dx + dy * dy + dz * dz); if (len > 0) { - motionX = (dx / len) * speed; - motionY = (dy / len) * speed; - motionZ = (dz / len) * speed; + motionX = (dx / len) * getSpeed(); + motionY = (dy / len) * getSpeed(); + motionZ = (dz / len) * getSpeed(); } } else if (owner != null) { float yaw = (float) Math.toRadians(owner.rotationYaw); float pitch = (float) Math.toRadians(owner.rotationPitch); - motionX = -Math.sin(yaw) * Math.cos(pitch) * speed; - motionY = -Math.sin(pitch) * speed; - motionZ = Math.cos(yaw) * Math.cos(pitch) * speed; + motionX = -Math.sin(yaw) * Math.cos(pitch) * getSpeed(); + motionY = -Math.sin(pitch) * getSpeed(); + motionZ = Math.cos(yaw) * Math.cos(pitch) * getSpeed(); } } @@ -264,7 +245,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { handleClientInterpolation(); } else { // Server-side logic - updateHoming(); + updateMovement(); checkBlockCollision(); checkEntityCollision(); this.moveEntity(motionX, motionY, motionZ); @@ -274,7 +255,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { if (this.isCollidedHorizontally || this.isCollidedVertically) { if (!worldObj.isRemote) { hasHit = true; - if (explosive) { + if (isExplosive()) { doExplosion(); } } @@ -292,10 +273,36 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { this.posZ += motionZ; } - private void updateHoming() { - if (!homing) return; + private void updateMovement() { + if (!isTrajectoryConcluded()) { + updateTrajectory(); + } else { + updateHoming(); + } + } - Entity target = getTarget(); + private void updateTrajectory() { + if (isTrajectoryConcluded()) return; + // i really fucking hate math + + } + + private boolean isTrajectoryConcluded() { + if (trajectoryData.isEmpty()) return true; + + for (int i = 0; i < trajectoryData.size(); i++) { + if (!trajectoryData.getPath(i).isConcluded()) { + return false; + } + } + + return true; + } + + private void updateHoming() { + if (!isHoming()) return; + + Entity target = getTargetEntity(); if (target == null || !target.isEntityAlive()) return; double dx = target.posX - posX; @@ -303,21 +310,21 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { double dz = target.posZ - posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist <= homingRange && dist > 0) { + if (dist <= getHomingRange() && dist > 0) { // Calculate effective homing strength - increases when closer to commit to target // This prevents orbiting behavior at close range - float effectiveStrength = homingStrength; - if (dist < homingRange * 0.3) { + float effectiveStrength = getHomingStrength(); + if (dist < getHomingRange() * 0.3) { // Within 30% of homing range, dramatically increase strength to commit - effectiveStrength = Math.min(1.0f, homingStrength * 2.5f); - } else if (dist < homingRange * 0.6) { + effectiveStrength = Math.min(1.0f, getHomingStrength() * 2.5f); + } else if (dist < getHomingRange() * 0.6) { // Within 60% of homing range, moderately increase strength - effectiveStrength = Math.min(0.8f, homingStrength * 1.5f); + effectiveStrength = Math.min(0.8f, getHomingStrength() * 1.5f); } - double desiredVX = (dx / dist) * speed; - double desiredVY = (dy / dist) * speed; - double desiredVZ = (dz / dist) * speed; + double desiredVX = (dx / dist) * getSpeed(); + double desiredVY = (dy / dist) * getSpeed(); + double desiredVZ = (dz / dist) * getSpeed(); motionX += (desiredVX - motionX) * effectiveStrength; motionY += (desiredVY - motionY) * effectiveStrength; @@ -326,9 +333,9 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { // Normalize to maintain speed double vLen = Math.sqrt(motionX * motionX + motionY * motionY + motionZ * motionZ); if (vLen > 0) { - motionX = (motionX / vLen) * speed; - motionY = (motionY / vLen) * speed; - motionZ = (motionZ / vLen) * speed; + motionX = (motionX / vLen) * getSpeed(); + motionY = (motionY / vLen) * getSpeed(); + motionZ = (motionZ / vLen) * getSpeed(); } } } @@ -341,7 +348,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { if (blockHit != null && blockHit.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { hasHit = true; - if (explosive) { + if (isExplosive()) { posX = blockHit.hitVec.xCoord; posY = blockHit.hitVec.yCoord; posZ = blockHit.hitVec.zCoord; @@ -366,7 +373,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { hasHit = true; - if (explosive) { + if (isExplosive()) { doExplosion(); } else { applyDamage(entity); @@ -383,7 +390,7 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { private void updateCharging() { chargeTick++; - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (owner == null || owner.isDead) { setDead(); return; @@ -420,22 +427,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { // ==================== GETTERS ==================== - public float getSpeed() { - return speed; - } - - public boolean isHoming() { - return homing; - } - - public float getHomingStrength() { - return homingStrength; - } - - public float getHomingRange() { - return homingRange; - } - // Legacy getter for renderer compatibility public float getOrbSize() { return size; @@ -445,10 +436,6 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { @Override protected void readProjectileNBT(NBTTagCompound nbt) { - this.speed = nbt.hasKey("OrbSpeed") ? nbt.getFloat("OrbSpeed") : 0.5f; - this.homing = !nbt.hasKey("Homing") || nbt.getBoolean("Homing"); - this.homingStrength = nbt.hasKey("HomingStrength") ? nbt.getFloat("HomingStrength") : 0.15f; - this.homingRange = nbt.hasKey("HomingRange") ? nbt.getFloat("HomingRange") : 20.0f; // Charging state boolean isCharging = nbt.hasKey("Charging") && nbt.getBoolean("Charging"); this.charging = isCharging; @@ -456,16 +443,10 @@ public class EntityAbilityOrb extends EntityAbilityProjectile { this.chargeDuration = nbt.hasKey("ChargeDuration") ? nbt.getInteger("ChargeDuration") : 40; this.chargeTick = nbt.hasKey("ChargeTick") ? nbt.getInteger("ChargeTick") : 0; this.targetSize = nbt.hasKey("TargetSize") ? nbt.getFloat("TargetSize") : this.size; - // Anchor data - this.anchorData.readNBT(nbt); } @Override protected void writeProjectileNBT(NBTTagCompound nbt) { - nbt.setFloat("OrbSpeed", speed); - nbt.setBoolean("Homing", homing); - nbt.setFloat("HomingStrength", homingStrength); - nbt.setFloat("HomingRange", homingRange); // Charging state nbt.setBoolean("Charging", isCharging()); nbt.setInteger("ChargeDuration", chargeDuration); diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index 57f99e1c8..7080ce2ef 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -4,11 +4,12 @@ import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.data.EnergyColorData; -import kamkeel.npcs.controllers.data.ability.data.EnergyCombatData; -import kamkeel.npcs.controllers.data.ability.data.EnergyLifespanData; -import kamkeel.npcs.controllers.data.ability.data.EnergyLightningData; +import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.IAbilityDamageHandler; +import kamkeel.npcs.controllers.data.ability.data.*; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -16,13 +17,16 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; -import net.minecraft.util.Vec3; import net.minecraft.world.World; import noppes.npcs.NpcDamageSource; +import noppes.npcs.api.entity.IEnergyProjectile; +import noppes.npcs.api.entity.IEntity; import noppes.npcs.entity.EntityNPCInterface; +import noppes.npcs.scripted.NpcAPI; import java.util.ArrayList; import java.util.List; +import java.util.Map; /** * Base class for all ability projectiles (Orb, Disc, Beam, Laser). @@ -30,55 +34,55 @@ import java.util.List; * * Design inspired by LouisXIV's energy attack system. */ -public abstract class EntityAbilityProjectile extends Entity implements IEntityAdditionalSpawnData { +public abstract class EntityAbilityProjectile extends Entity implements IEnergyProjectile, IEntityAdditionalSpawnData { // ==================== VISUAL PROPERTIES ==================== protected float size = 1.0f; - protected int innerColor = 0xFFFFFF; - protected int outerColor = 0x8888FF; - protected boolean outerColorEnabled = true; - protected float outerColorWidth = 0.4f; // Additive offset from inner size - protected float outerColorAlpha = 0.5f; - protected float rotationSpeed = 4.0f; // ==================== COMBAT PROPERTIES ==================== - protected float damage = 7.0f; - protected float knockback = 1.0f; - protected float knockbackUp = 0.1f; + protected EnergyCombatData combatData = new EnergyCombatData(); // ==================== EFFECT PROPERTIES ==================== protected List effects = new ArrayList<>(); - // ==================== EXPLOSION PROPERTIES ==================== - protected boolean explosive = false; - protected float explosionRadius = 3.0f; - protected float explosionDamageFalloff = 0.5f; - // ==================== LIGHTNING EFFECT PROPERTIES ==================== - protected boolean lightningEffect = false; - protected float lightningDensity = 0.15f; // Bolts spawned per tick (0.15 = ~15% chance per frame) - protected float lightningRadius = 0.5f; // Max distance lightning can arc from center - protected int lightningFadeTime = 6; // Ticks before lightning fades out + protected EnergyLightningData lightningData = new EnergyLightningData(); // Client-side lightning state (not saved to NBT) @cpw.mods.fml.relauncher.SideOnly(cpw.mods.fml.relauncher.Side.CLIENT) public transient Object lightningState; // Actually AttachedLightningRenderer.LightningState - // ==================== LIFESPAN ==================== - protected float maxDistance = 30.0f; - protected int maxLifetime = 200; + // ==================== DISPLAY PROPERTIES ==================== + protected EnergyDisplayData displayData = new EnergyDisplayData(); + + // ==================== ANCHOR PROPERTIES ==================== + protected EnergyAnchorData anchorData = new EnergyAnchorData(AnchorPoint.FRONT); + + // ==================== LIFESPAN PROPERTIES ==================== + protected EnergyLifespanData lifespanData = new EnergyLifespanData(); protected long deathWorldTime = -1; // World time when entity should die (-1 = not set) + // ==================== HOMING PROPERTIES ==================== + protected EnergyHomingData homingData = new EnergyHomingData(); + + // ==================== TRAJECTORY PROPERTIES ==================== + protected EnergyTrajectoryData trajectoryData = new EnergyTrajectoryData(); + protected Map pathDelays; + // ==================== TRACKING ==================== protected double startX, startY, startZ; protected int ownerEntityId = -1; protected int targetEntityId = -1; + protected int siblingEntityId = -1; // ==================== STATE ==================== protected boolean hasHit = false; protected boolean previewMode = false; // Client-side preview mode (no damage/effects) protected EntityLivingBase previewOwner = null; // Direct reference for GUI preview (no world lookup) + /** The ability that spawned this projectile. Transient, not saved to NBT. */ + protected transient Ability sourceAbility = null; + // ==================== ROTATION INTERPOLATION ==================== public float prevRotationValX, prevRotationValY, prevRotationValZ; public float rotationValX, rotationValY, rotationValZ; @@ -103,10 +107,11 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA /** * Initialize common properties using data classes. Call from subclass constructors. */ - protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, - double x, double y, double z, float size, - EnergyColorData color, EnergyCombatData combat, - EnergyLightningData lightning, EnergyLifespanData lifespan) { + protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, EntityAbilityProjectile sibling, + double x, double y, double z, float size, + EnergyDisplayData display, EnergyCombatData combat, + EnergyLightningData lightning, EnergyLifespanData lifespan, + EnergyTrajectoryData trajectory) { this.setPosition(x, y, z); this.startX = x; this.startY = y; @@ -114,42 +119,31 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA this.ownerEntityId = owner.getEntityId(); this.targetEntityId = target != null ? target.getEntityId() : -1; + this.siblingEntityId = sibling != null ? sibling.getEntityId() : -1; // Visual this.size = size; - this.innerColor = color.innerColor; - this.outerColor = color.outerColor; - this.outerColorEnabled = color.outerColorEnabled; - this.outerColorWidth = color.outerColorWidth; - this.outerColorAlpha = color.outerColorAlpha; - this.rotationSpeed = color.rotationSpeed; - // Combat - this.damage = combat.damage; - this.knockback = combat.knockback; - this.knockbackUp = combat.knockbackUp; - - // Explosion - this.explosive = combat.explosive; - this.explosionRadius = combat.explosionRadius; - this.explosionDamageFalloff = combat.explosionDamageFalloff; - - // Lifespan - this.maxDistance = lifespan.maxDistance; - this.maxLifetime = lifespan.maxLifetime; - // deathWorldTime will be set on first tick when world is available - - // Lightning - this.lightningEffect = lightning.lightningEffect; - this.lightningDensity = lightning.lightningDensity; - this.lightningRadius = lightning.lightningRadius; - this.lightningFadeTime = lightning.lightningFadeTime; + this.displayData = display; + this.combatData = combat; + this.lifespanData = lifespan; // deathWorldTime will be set on first tick when world is available + this.lightningData = lightning; + this.trajectoryData = trajectory; // Initialize render size this.renderCurrentSize = size; this.prevRenderSize = size; } + // Initialize projectile without a sibling + protected void initProjectile(EntityLivingBase owner, EntityLivingBase target, + double x, double y, double z, float size, + EnergyDisplayData display, EnergyCombatData combat, + EnergyLightningData lightning, EnergyLifespanData lifespan, + EnergyTrajectoryData trajectory) { + initProjectile(owner, target, null, x, y, z, size, display, combat, lightning, lifespan, trajectory); + } + @Override protected void entityInit() { // No DataWatcher needed - using IEntityAdditionalSpawnData with NBT @@ -192,9 +186,22 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA // Skip lifetime/distance checks in preview mode if (!previewMode) { + // Failsafe: if owner entity is gone, dead, or NPC was killed/reset, self-destruct + if (ownerEntityId >= 0 && ticksExisted > 5) { + Entity owner = worldObj.getEntityByID(ownerEntityId); + if (owner == null || owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { + this.setDead(); + return; + } + } + // Set death time on first tick if not already set (handles chunk load/unload) if (deathWorldTime < 0 && worldObj != null) { - deathWorldTime = worldObj.getTotalWorldTime() + maxLifetime; + deathWorldTime = worldObj.getTotalWorldTime() + getMaxLifetime(); } // Check lifespan using world time (survives chunk unload/reload) @@ -223,9 +230,9 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA * Update rotation values. Override for custom rotation behavior. */ protected void updateRotation() { - this.rotationValX += rotationSpeed * 0.7f; - this.rotationValY += rotationSpeed; - this.rotationValZ += rotationSpeed * 0.5f; + this.rotationValX += getRotationSpeed() * 0.7f; + this.rotationValY += getRotationSpeed(); + this.rotationValZ += getRotationSpeed() * 0.5f; if (this.rotationValX > 360.0f) this.rotationValX -= 360.0f; if (this.rotationValY > 360.0f) this.rotationValY -= 360.0f; @@ -242,7 +249,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA (posY - startY) * (posY - startY) + (posZ - startZ) * (posZ - startZ) ); - return distTraveled >= maxDistance; + return distTraveled >= getMaxDistance(); } /** @@ -314,21 +321,37 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA protected void applyDamage(EntityLivingBase target) { if (previewMode) return; // Skip damage in preview mode - applyDamage(target, this.damage, this.knockback); + applyDamage(target, this.getDamage(), this.getKnockback()); } protected void applyDamage(EntityLivingBase target, float dmg, float kb) { if (previewMode) return; // Skip damage in preview mode - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); - if (owner instanceof EntityNPCInterface) { - target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmg); - } else if (owner instanceof EntityPlayer) { - target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmg); - } else if (owner instanceof EntityLivingBase) { - target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmg); - } else { - target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmg); + // Check for external damage handler (e.g., DBC Addon) + boolean handled = false; + if (sourceAbility != null && owner instanceof EntityLivingBase) { + IAbilityDamageHandler handler = AbilityController.Instance.getDamageHandler(); + if (handler != null) { + double dx = target.posX - posX; + double dz = target.posZ - posZ; + float kbUp = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1f; + handled = handler.handleDamage(sourceAbility, (EntityLivingBase) owner, target, + dmg, kb, kbUp, dx, dz); + } + } + + if (!handled) { + // Default damage path + if (owner instanceof EntityNPCInterface) { + target.attackEntityFrom(new NpcDamageSource("npc_ability", (EntityNPCInterface) owner), dmg); + } else if (owner instanceof EntityPlayer) { + target.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) owner), dmg); + } else if (owner instanceof EntityLivingBase) { + target.attackEntityFrom(DamageSource.causeMobDamage((EntityLivingBase) owner), dmg); + } else { + target.attackEntityFrom(new NpcDamageSource("npc_ability", null), dmg); + } } if (kb > 0) { @@ -338,7 +361,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA if (len > 0) { double kbX = (dx / len) * kb * 0.5; double kbZ = (dz / len) * kb * 0.5; - double kbY = knockbackUp > 0 ? knockbackUp : 0.1; + double kbY = getKnockbackUp() > 0 ? getKnockbackUp() : 0.1; target.addVelocity(kbX, kbY, kbZ); target.velocityChanged = true; } @@ -360,15 +383,30 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA this.effects = effects != null ? effects : new ArrayList<>(); } + /** + * Set the source ability that spawned this projectile. + * Used by external damage handlers to access ability-specific data. + */ + public void setSourceAbility(Ability ability) { + this.sourceAbility = ability; + } + + /** + * Get the source ability that spawned this projectile. + */ + public Ability getSourceAbility() { + return sourceAbility; + } + protected void doExplosion() { if (previewMode) return; // Skip explosion in preview mode worldObj.playSoundEffect(posX, posY, posZ, "random.explode", 1.0f, 1.0f); - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); AxisAlignedBB explosionBox = AxisAlignedBB.getBoundingBox( - posX - explosionRadius, posY - explosionRadius, posZ - explosionRadius, - posX + explosionRadius, posY + explosionRadius, posZ + explosionRadius + posX - getExplosionRadius(), posY - getExplosionRadius(), posZ - getExplosionRadius(), + posX + getExplosionRadius(), posY + getExplosionRadius(), posZ + getExplosionRadius() ); @SuppressWarnings("unchecked") @@ -383,16 +421,16 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA Math.pow(target.posZ - posZ, 2) ); - if (dist <= explosionRadius) { - float falloff = 1.0f - (float) (dist / explosionRadius) * explosionDamageFalloff; - applyDamage(target, damage * falloff, knockback * falloff); + if (dist <= getExplosionRadius()) { + float falloff = 1.0f - (float) (dist / getExplosionRadius()) * getExplosionDamageFalloff(); + applyDamage(target, getDamage() * falloff, getKnockback() * falloff); } } } // ==================== ENTITY HELPERS ==================== - protected Entity getOwner() { + public Entity getOwnerEntity() { // In preview mode, use direct reference (no world lookup) if (previewMode && previewOwner != null) { return previewOwner; @@ -401,6 +439,18 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA return worldObj.getEntityByID(ownerEntityId); } + @Override + public int getOwnerEntityId() { + return ownerEntityId; + } + + @Override + public IEntity getOwner() { + if (previewMode) return null; + if (getOwnerEntity() == null) return null; + return NpcAPI.Instance().getIEntity(getOwnerEntity()); + } + /** * Set the preview owner for GUI preview mode. * This allows anchor point calculations without world entity lookup. @@ -409,16 +459,45 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA this.previewOwner = owner; } - protected Entity getTarget() { + @Override + public int getTargetEntityId() { + return targetEntityId; + } + + public Entity getTargetEntity() { if (targetEntityId == -1) return null; return worldObj.getEntityByID(targetEntityId); } + @Override + public IEntity getTarget() { + if (getTargetEntity() == null) return null; + return NpcAPI.Instance().getIEntity(getTargetEntity()); + } + + @Override + public int getSiblingEntityId() { + return siblingEntityId; + } + + @Override + public void setSiblingEntityId(int siblingEntityId) { + if (!(worldObj.getEntityByID(siblingEntityId) instanceof EntityAbilityProjectile)) return; + + this.siblingEntityId = siblingEntityId; + } + + @Override + public IEnergyProjectile getSibling() { + if (siblingEntityId == -1) return null; + return (EntityAbilityProjectile) worldObj.getEntityByID(siblingEntityId); + } + /** * Check if an entity should be ignored for collision. */ protected boolean shouldIgnoreEntity(Entity entity) { - Entity owner = getOwner(); + Entity owner = getOwnerEntity(); if (entity == owner) return true; if (owner instanceof EntityNPCInterface && entity instanceof EntityNPCInterface) { @@ -426,73 +505,170 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA EntityNPCInterface targetNpc = (EntityNPCInterface) entity; if (ownerNpc.faction.id == targetNpc.faction.id) return true; } + + if (entity.getEntityId() == getSiblingEntityId()) + return true; + return false; } // ==================== VISUAL GETTERS ==================== + @Override public float getSize() { return size; } + @Override public int getInnerColor() { - return innerColor; + return displayData.getInnerColor(); } + @Override public int getOuterColor() { - return outerColor; + return displayData.getOuterColor(); } + @Override public boolean isOuterColorEnabled() { - return outerColorEnabled; + return displayData.isOuterColorEnabled(); } + @Override public float getOuterColorWidth() { - return outerColorWidth; + return displayData.getOuterColorWidth(); } + @Override public float getOuterColorAlpha() { - return outerColorAlpha; + return displayData.getOuterColorAlpha(); } + @Override public float getRotationSpeed() { - return rotationSpeed; + return displayData.getRotationSpeed(); } + // ==================== ROTATION GETTERS ==================== + + @Override public float getInterpolatedRotationX(float partialTicks) { return this.prevRotationValX + (this.rotationValX - this.prevRotationValX) * partialTicks; } + @Override public float getInterpolatedRotationY(float partialTicks) { return this.prevRotationValY + (this.rotationValY - this.prevRotationValY) * partialTicks; } + @Override public float getInterpolatedRotationZ(float partialTicks) { return this.prevRotationValZ + (this.rotationValZ - this.prevRotationValZ) * partialTicks; } + @Override public float getInterpolatedSize(float partialTicks) { return this.prevRenderSize + (this.renderCurrentSize - this.prevRenderSize) * partialTicks; } // ==================== LIGHTNING GETTERS ==================== + @Override public boolean hasLightningEffect() { - return lightningEffect; + return lightningData.isLightningEffect(); } + @Override public float getLightningDensity() { - return lightningDensity; + return lightningData.getLightningDensity(); } + @Override public float getLightningRadius() { - return lightningRadius; + return lightningData.getLightningRadius(); } + @Override public int getLightningFadeTime() { - return lightningFadeTime; + return lightningData.getLightningFadeTime(); } + // ==================== LIFESPAN GETTERS ==================== + + @Override + public float getMaxDistance() { return lifespanData.getMaxDistance(); } + + @Override + public int getMaxLifetime() { return lifespanData.getMaxLifetime(); } + + // ==================== COMBAT GETTERS ==================== + + @Override + public float getDamage() { return combatData.getDamage(); } + + @Override + public float getKnockback() { return combatData.knockback; } + + @Override + public float getKnockbackUp() { return combatData.knockbackUp; } + + @Override + public boolean isExplosive() { return combatData.isExplosive(); } + + @Override + public float getExplosionRadius() { return combatData.explosionRadius; } + + @Override + public float getExplosionDamageFalloff() { return combatData.explosionDamageFalloff; } + + // ==================== HOMING GETTERS ==================== + + @Override + public boolean isHoming() { return homingData.isHoming(); } + + @Override + public float getHomingStrength() { return homingData.getHomingStrength(); } + + @Override + public float getHomingRange() { return homingData.getHomingRange(); } + + // ==================== TRAJECTORY GETTERS ==================== + + + + // ==================== ANCHOR GETTERS ==================== + + @Override + public float getSpeed() { return homingData.getSpeed(); } + + public AnchorPoint getAnchorPoint() { return anchorData.getAnchorPoint(); } + + @Override + public int getAnchor() { return anchorData.getAnchor(); } + + @Override + public float getAnchorOffsetX() { return anchorData.getAnchorOffsetX(); } + + @Override + public float getAnchorOffsetY() { return anchorData.getAnchorOffsetY(); } + + @Override + public float getAnchorOffsetZ() { return anchorData.getAnchorOffsetZ(); } + + // ==================== MOVEMENT GETTERS ==================== + + @Override public double getStartX() { return startX; } + + @Override public double getStartY() { return startY; } + + @Override public double getStartZ() { return startZ; } + + @Override public double getMotionX() { return motionX; } + + @Override public double getMotionY() { return motionY; } + + @Override public double getMotionZ() { return motionZ; } + // ==================== BRIGHTNESS ==================== @Override @@ -525,20 +701,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA */ protected void readBaseNBT(NBTTagCompound nbt) { this.size = nbt.getFloat("Size"); - this.innerColor = nbt.getInteger("InnerColor"); - this.outerColor = nbt.getInteger("OuterColor"); - this.outerColorEnabled = !nbt.hasKey("OuterColorEnabled") || nbt.getBoolean("OuterColorEnabled"); - this.outerColorAlpha = nbt.hasKey("OuterColorAlpha") ? nbt.getFloat("OuterColorAlpha") : 0.5f; - this.outerColorWidth = nbt.hasKey("OuterColorWidth") ? nbt.getFloat("OuterColorWidth") : 0.4f; - this.rotationSpeed = nbt.hasKey("RotationSpeed") ? nbt.getFloat("RotationSpeed") : 4.0f; - - this.damage = nbt.getFloat("Damage"); - this.knockback = nbt.getFloat("Knockback"); - this.knockbackUp = nbt.getFloat("KnockbackUp"); - - this.explosive = nbt.getBoolean("Explosive"); - this.explosionRadius = nbt.getFloat("ExplosionRadius"); - this.explosionDamageFalloff = nbt.getFloat("ExplosionDamageFalloff"); // Read effects list this.effects.clear(); @@ -549,8 +711,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA } } - this.maxDistance = nbt.getFloat("MaxDistance"); - this.maxLifetime = nbt.getInteger("MaxLifetime"); this.deathWorldTime = nbt.hasKey("DeathWorldTime") ? nbt.getLong("DeathWorldTime") : -1; this.startX = nbt.getDouble("StartX"); @@ -559,21 +719,24 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA this.ownerEntityId = nbt.getInteger("OwnerId"); this.targetEntityId = nbt.getInteger("TargetId"); + this.siblingEntityId = nbt.getInteger("SiblingId"); this.motionX = nbt.getDouble("MotionX"); this.motionY = nbt.getDouble("MotionY"); this.motionZ = nbt.getDouble("MotionZ"); - // Lightning - this.lightningEffect = nbt.getBoolean("LightningEffect"); - this.lightningDensity = nbt.hasKey("LightningDensity") ? nbt.getFloat("LightningDensity") : 0.15f; - this.lightningRadius = nbt.hasKey("LightningRadius") ? nbt.getFloat("LightningRadius") : 0.5f; - this.lightningFadeTime = nbt.hasKey("LightningFadeTime") ? nbt.getInteger("LightningFadeTime") : 6; - if (this.worldObj != null && this.worldObj.isRemote) { this.renderCurrentSize = this.size; this.prevRenderSize = this.size; } + + anchorData.readNBT(nbt); + combatData.readNBT(nbt); + displayData.readNBT(nbt); + homingData.readNBT(nbt); + lifespanData.readNBT(nbt); + lightningData.readNBT(nbt); + trajectoryData.readNBT(nbt); } /** @@ -581,20 +744,6 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA */ protected void writeBaseNBT(NBTTagCompound nbt) { nbt.setFloat("Size", size); - nbt.setInteger("InnerColor", innerColor); - nbt.setInteger("OuterColor", outerColor); - nbt.setBoolean("OuterColorEnabled", outerColorEnabled); - nbt.setFloat("OuterColorWidth", outerColorWidth); - nbt.setFloat("OuterColorAlpha", outerColorAlpha); - nbt.setFloat("RotationSpeed", rotationSpeed); - - nbt.setFloat("Damage", damage); - nbt.setFloat("Knockback", knockback); - nbt.setFloat("KnockbackUp", knockbackUp); - - nbt.setBoolean("Explosive", explosive); - nbt.setFloat("ExplosionRadius", explosionRadius); - nbt.setFloat("ExplosionDamageFalloff", explosionDamageFalloff); // Write effects list if (!effects.isEmpty()) { @@ -605,9 +754,7 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA nbt.setTag("Effects", effectsList); } - nbt.setFloat("MaxDistance", maxDistance); nbt.setLong("DeathWorldTime", deathWorldTime); - nbt.setInteger("MaxLifetime", maxLifetime); nbt.setDouble("StartX", startX); nbt.setDouble("StartY", startY); @@ -615,16 +762,19 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA nbt.setInteger("OwnerId", ownerEntityId); nbt.setInteger("TargetId", targetEntityId); + nbt.setInteger("SiblingId", targetEntityId); nbt.setDouble("MotionX", motionX); nbt.setDouble("MotionY", motionY); nbt.setDouble("MotionZ", motionZ); - // Lightning - nbt.setBoolean("LightningEffect", lightningEffect); - nbt.setFloat("LightningDensity", lightningDensity); - nbt.setFloat("LightningRadius", lightningRadius); - nbt.setInteger("LightningFadeTime", lightningFadeTime); + anchorData.writeNBT(nbt); + combatData.writeNBT(nbt); + displayData.writeNBT(nbt); + homingData.writeNBT(nbt); + lifespanData.writeNBT(nbt); + lightningData.writeNBT(nbt); + trajectoryData.writeNBT(nbt); } /** diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java index 8540d4df9..4d072090e 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilitySweeper.java @@ -4,7 +4,7 @@ import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; -import kamkeel.npcs.controllers.data.ability.data.EnergyColorData; +import kamkeel.npcs.controllers.data.ability.data.EnergyDisplayData; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -60,6 +60,10 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa private int maxTicks = 400; private long deathWorldTime = -1; + // Preview mode + private boolean previewMode = false; + private EntityLivingBase previewOwner = null; + // Damage state private transient int ticksSinceDamage = 0; private transient Set hitThisTick = new HashSet<>(); @@ -74,7 +78,7 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa public EntityAbilitySweeper(World world, EntityLivingBase owner, EntityLivingBase target, float beamLength, float beamWidth, float beamHeight, - EnergyColorData colorData, + EnergyDisplayData displayData, float sweepSpeed, int numberOfRotations, float damage, int damageInterval, boolean piercing, boolean lockOnTarget) { @@ -85,10 +89,10 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa this.beamLength = beamLength; this.beamWidth = beamWidth; this.beamHeight = beamHeight; - this.innerColor = colorData.innerColor; - this.outerColor = colorData.outerColor; - this.outerColorEnabled = colorData.outerColorEnabled; - this.outerColorWidth = colorData.outerColorWidth; + this.innerColor = displayData.innerColor; + this.outerColor = displayData.outerColor; + this.outerColorEnabled = displayData.outerColorEnabled; + this.outerColorWidth = displayData.outerColorWidth; this.sweepSpeed = sweepSpeed; this.numberOfRotations = numberOfRotations; this.damage = damage; @@ -281,7 +285,16 @@ public class EntityAbilitySweeper extends Entity implements IEntityAdditionalSpa target.velocityChanged = true; } + /** + * Set up preview mode. Owner is stored directly since world entity lookup won't work. + */ + public void setupPreview(EntityLivingBase owner) { + this.previewMode = true; + this.previewOwner = owner; + } + private Entity getOwner() { + if (previewMode && previewOwner != null) return previewOwner; if (ownerEntityId == -1) return null; return worldObj.getEntityByID(ownerEntityId); } diff --git a/src/main/java/kamkeel/npcs/network/PacketHandler.java b/src/main/java/kamkeel/npcs/network/PacketHandler.java index 63ab9b192..bcfd18abd 100644 --- a/src/main/java/kamkeel/npcs/network/PacketHandler.java +++ b/src/main/java/kamkeel/npcs/network/PacketHandler.java @@ -108,6 +108,9 @@ import kamkeel.npcs.network.packets.request.bank.BankSavePacket; import kamkeel.npcs.network.packets.request.bank.BanksGetPacket; import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket; import kamkeel.npcs.network.packets.request.clone.CloneAllTagsShortPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderCrudPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; +import kamkeel.npcs.network.packets.request.clone.CloneMovePacket; import kamkeel.npcs.network.packets.request.clone.CloneListPacket; import kamkeel.npcs.network.packets.request.clone.ClonePreSavePacket; import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket; @@ -325,6 +328,9 @@ public class PacketHandler { REQUEST_PACKET.registerPacket(new CloneTagListPacket()); REQUEST_PACKET.registerPacket(new CloneAllTagsPacket()); REQUEST_PACKET.registerPacket(new CloneAllTagsShortPacket()); + REQUEST_PACKET.registerPacket(new CloneFolderListPacket()); + REQUEST_PACKET.registerPacket(new CloneFolderCrudPacket()); + REQUEST_PACKET.registerPacket(new CloneMovePacket()); // Linked Packets diff --git a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java index 8183941d0..2f3e6ea94 100644 --- a/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java +++ b/src/main/java/kamkeel/npcs/network/enums/EnumRequestPacket.java @@ -163,6 +163,9 @@ public enum EnumRequestPacket { CloneAllTags, CloneAllTagsShort, ClonePreSave, + CloneFolderList, + CloneFolderCrud, + CloneMove, EventScript, PlayerScript, diff --git a/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java b/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java index 2717d6277..75e0c40ae 100644 --- a/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/data/LoginPacket.java @@ -16,7 +16,9 @@ import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.client.AuctionClientConfig; import noppes.npcs.client.ClientCacheHandler; import noppes.npcs.config.ConfigMain; +import noppes.npcs.client.ScriptClientConfig; import noppes.npcs.controllers.AuctionConfigSync; +import noppes.npcs.controllers.ScriptConfigSync; import java.io.IOException; import java.util.EnumMap; @@ -65,6 +67,11 @@ public final class LoginPacket extends AbstractPacket { NBTTagCompound auctionConfig = new NBTTagCompound(); AuctionConfigSync.writeToNBT(auctionConfig); ByteBufUtils.writeNBT(out, auctionConfig); + + // Send script config (server-side sync) + NBTTagCompound scriptConfig = new NBTTagCompound(); + ScriptConfigSync.writeToNBT(scriptConfig); + ByteBufUtils.writeNBT(out, scriptConfig); } @SideOnly(Side.CLIENT) @@ -88,6 +95,10 @@ public final class LoginPacket extends AbstractPacket { NBTTagCompound auctionConfig = ByteBufUtils.readNBT(in); AuctionClientConfig.readFromNBT(auctionConfig); + // Read script config + NBTTagCompound scriptConfig = ByteBufUtils.readNBT(in); + ScriptClientConfig.readFromNBT(scriptConfig); + PacketClient.sendClient(new SyncRevisionInfoPacket( serverKey, ClientCacheHandler.getLastServerKey(), diff --git a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java index 48ac3391b..a58b896f4 100644 --- a/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/player/SpecialKeyStatePacket.java @@ -59,6 +59,16 @@ public final class SpecialKeyStatePacket extends AbstractPacket { // Trigger ability activation on key press (rising edge) if (keyDown && !wasDown) { + // Don't activate if player has a GUI open (not the default inventory) + if (player.openContainer != null && !(player.openContainer instanceof net.minecraft.inventory.ContainerPlayer)) { + return; + } + + // Don't activate if player is riding an entity (mount) + if (player.ridingEntity != null) { + return; + } + data.abilityData.activateAbility(player); } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderCrudPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderCrudPacket.java new file mode 100644 index 000000000..061700e35 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderCrudPacket.java @@ -0,0 +1,111 @@ +package kamkeel.npcs.network.packets.request.clone; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.controllers.ServerCloneController; +import noppes.npcs.controllers.data.CloneFolder; + +import java.io.IOException; + +public final class CloneFolderCrudPacket extends AbstractPacket { + public static String packetName = "Request|CloneFolderCrud"; + + public static final byte ACTION_CREATE = 0; + public static final byte ACTION_RENAME = 1; + public static final byte ACTION_DELETE = 2; + + private byte action; + private String name; + private String newName; + + public CloneFolderCrudPacket() { + } + + public CloneFolderCrudPacket(byte action, String name) { + this.action = action; + this.name = name; + this.newName = ""; + } + + public CloneFolderCrudPacket(byte action, String name, String newName) { + this.action = action; + this.name = name; + this.newName = newName; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CloneFolderCrud; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.NPC_CLONE; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + out.writeByte(action); + ByteBufUtils.writeString(out, name); + if (action == ACTION_RENAME) { + ByteBufUtils.writeString(out, newName); + } + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER)) + return; + + byte action = in.readByte(); + String name = ByteBufUtils.readString(in); + + boolean success = false; + switch (action) { + case ACTION_CREATE: + if (CloneFolder.isValidName(name)) + success = ServerCloneController.Instance.createFolder(name) != null; + break; + case ACTION_RENAME: + String newName = ByteBufUtils.readString(in); + if (CloneFolder.isValidName(newName)) + success = ServerCloneController.Instance.renameFolder(name, newName); + break; + case ACTION_DELETE: + success = ServerCloneController.Instance.deleteFolder(name); + break; + } + + NBTTagCompound compound = new NBTTagCompound(); + compound.setBoolean("Success", success); + NBTTagList folderList = new NBTTagList(); + for (CloneFolder folder : ServerCloneController.Instance.getFolderList()) { + folderList.appendTag(folder.writeNBT(new NBTTagCompound())); + } + compound.setTag("CloneFolders", folderList); + + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderListPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderListPacket.java new file mode 100644 index 000000000..b7e7fe9f8 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneFolderListPacket.java @@ -0,0 +1,59 @@ +package kamkeel.npcs.network.packets.request.clone; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import noppes.npcs.controllers.ServerCloneController; +import noppes.npcs.controllers.data.CloneFolder; + +import java.io.IOException; + +public final class CloneFolderListPacket extends AbstractPacket { + public static String packetName = "Request|CloneFolderList"; + + public CloneFolderListPacket() { + } + + @Override + public Enum getType() { + return EnumRequestPacket.CloneFolderList; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER)) + return; + + NBTTagCompound compound = new NBTTagCompound(); + NBTTagList folderList = new NBTTagList(); + for (CloneFolder folder : ServerCloneController.Instance.getFolderList()) { + folderList.appendTag(folder.writeNBT(new NBTTagCompound())); + } + compound.setTag("CloneFolders", folderList); + + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java index 87bac4a29..e6ce35f40 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneListPacket.java @@ -23,9 +23,16 @@ public final class CloneListPacket extends AbstractPacket { public static String packetName = "Request|CloneList"; private int tab; + private String folderName; public CloneListPacket(int tab) { this.tab = tab; + this.folderName = null; + } + + public CloneListPacket(String folderName) { + this.tab = -1; + this.folderName = folderName; } public CloneListPacket() { @@ -45,6 +52,9 @@ public final class CloneListPacket extends AbstractPacket { @Override public void sendData(ByteBuf out) throws IOException { out.writeInt(tab); + if (tab == -1) { + kamkeel.npcs.util.ByteBufUtils.writeString(out, folderName); + } } @Override @@ -54,14 +64,26 @@ public final class CloneListPacket extends AbstractPacket { if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.MOUNTER, EnumItemPacketType.CLONER)) return; - NBTTagList list = new NBTTagList(); int tab = in.readInt(); - for (String name : ServerCloneController.Instance.getClones(tab)) - list.appendTag(new NBTTagString(name)); + String folder = null; + if (tab == -1) { + folder = kamkeel.npcs.util.ByteBufUtils.readString(in); + } + NBTTagList list = new NBTTagList(); NBTTagList listDate = new NBTTagList(); - for (String name : ServerCloneController.Instance.getClonesDate(tab)) - listDate.appendTag(new NBTTagString(name)); + + if (folder != null) { + for (String name : ServerCloneController.Instance.getClones(folder)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(folder)) + listDate.appendTag(new NBTTagString(name)); + } else { + for (String name : ServerCloneController.Instance.getClones(tab)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(tab)) + listDate.appendTag(new NBTTagString(name)); + } NBTTagCompound compound = new NBTTagCompound(); compound.setTag("List", list); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneMovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneMovePacket.java new file mode 100644 index 000000000..124bd5204 --- /dev/null +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneMovePacket.java @@ -0,0 +1,97 @@ +package kamkeel.npcs.network.packets.request.clone; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import io.netty.buffer.ByteBuf; +import kamkeel.npcs.network.AbstractPacket; +import kamkeel.npcs.network.PacketChannel; +import kamkeel.npcs.network.PacketHandler; +import kamkeel.npcs.network.PacketUtil; +import kamkeel.npcs.network.enums.EnumItemPacketType; +import kamkeel.npcs.network.enums.EnumRequestPacket; +import kamkeel.npcs.network.packets.data.large.GuiDataPacket; +import kamkeel.npcs.util.ByteBufUtils; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcsPermissions; +import noppes.npcs.controllers.ServerCloneController; + +import java.io.IOException; + +public final class CloneMovePacket extends AbstractPacket { + public static String packetName = "Request|CloneMove"; + + private String cloneName; + private int fromTab; + private String fromFolder; + private int toTab; + private String toFolder; + + public CloneMovePacket() { + } + + public CloneMovePacket(String cloneName, int fromTab, String fromFolder, int toTab, String toFolder) { + this.cloneName = cloneName; + this.fromTab = fromTab; + this.fromFolder = fromFolder; + this.toTab = toTab; + this.toFolder = toFolder; + } + + @Override + public Enum getType() { + return EnumRequestPacket.CloneMove; + } + + @Override + public PacketChannel getChannel() { + return PacketHandler.REQUEST_PACKET; + } + + @Override + public CustomNpcsPermissions.Permission getPermission() { + return CustomNpcsPermissions.NPC_CLONE; + } + + @SideOnly(Side.CLIENT) + @Override + public void sendData(ByteBuf out) throws IOException { + ByteBufUtils.writeString(out, cloneName); + out.writeInt(fromTab); + ByteBufUtils.writeString(out, fromFolder != null ? fromFolder : ""); + out.writeInt(toTab); + ByteBufUtils.writeString(out, toFolder != null ? toFolder : ""); + } + + @Override + public void receiveData(ByteBuf in, EntityPlayer player) throws IOException { + if (!(player instanceof EntityPlayerMP)) + return; + if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER)) + return; + + String cloneName = ByteBufUtils.readString(in); + int fromTab = in.readInt(); + String fromFolder = ByteBufUtils.readString(in); + if (fromFolder.isEmpty()) fromFolder = null; + int toTab = in.readInt(); + String toFolder = ByteBufUtils.readString(in); + if (toFolder.isEmpty()) toFolder = null; + + boolean success = false; + if (fromFolder != null && toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder); + } else if (fromFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab); + } else if (toFolder != null) { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder); + } else { + success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab); + } + + NBTTagCompound compound = new NBTTagCompound(); + compound.setBoolean("MoveSuccess", success); + GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); + } +} diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java index 378145ddb..4d36eb531 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/ClonePreSavePacket.java @@ -24,6 +24,7 @@ public final class ClonePreSavePacket extends AbstractPacket { private String name; private int tab; + private String folderName; public ClonePreSavePacket() { } @@ -31,6 +32,13 @@ public final class ClonePreSavePacket extends AbstractPacket { public ClonePreSavePacket(String name, int tab) { this.name = name; this.tab = tab; + this.folderName = null; + } + + public ClonePreSavePacket(String name, String folderName) { + this.name = name; + this.tab = -1; + this.folderName = folderName; } @Override @@ -53,6 +61,9 @@ public final class ClonePreSavePacket extends AbstractPacket { public void sendData(ByteBuf out) throws IOException { ByteBufUtils.writeString(out, this.name); out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } } @Override @@ -62,7 +73,15 @@ public final class ClonePreSavePacket extends AbstractPacket { if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.CLONER)) return; - boolean bo = ServerCloneController.Instance.getCloneData(null, ByteBufUtils.readString(in), in.readInt()) != null; + String name = ByteBufUtils.readString(in); + int tab = in.readInt(); + boolean bo; + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + bo = ServerCloneController.Instance.getCloneData(null, name, folder) != null; + } else { + bo = ServerCloneController.Instance.getCloneData(null, name, tab) != null; + } NBTTagCompound compound = new NBTTagCompound(); compound.setBoolean("NameExists", bo); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java index ce1fcb367..96069f414 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneRemovePacket.java @@ -25,6 +25,7 @@ public final class CloneRemovePacket extends AbstractPacket { public static String packetName = "Request|CloneRemove"; private int tab; + private String folderName; private String name; public CloneRemovePacket() { @@ -32,6 +33,13 @@ public final class CloneRemovePacket extends AbstractPacket { public CloneRemovePacket(int tab, String name) { this.tab = tab; + this.folderName = null; + this.name = name; + } + + public CloneRemovePacket(String folderName, String name) { + this.tab = -1; + this.folderName = folderName; this.name = name; } @@ -54,6 +62,9 @@ public final class CloneRemovePacket extends AbstractPacket { @Override public void sendData(ByteBuf out) throws IOException { out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } ByteBufUtils.writeString(out, this.name); } @@ -65,16 +76,28 @@ public final class CloneRemovePacket extends AbstractPacket { return; int tab = in.readInt(); - ServerCloneController.Instance.removeClone(ByteBufUtils.readString(in), tab); + String folder = null; + if (tab == -1) { + folder = ByteBufUtils.readString(in); + } + String cloneName = ByteBufUtils.readString(in); NBTTagList list = new NBTTagList(); - - for (String name : ServerCloneController.Instance.getClones(tab)) - list.appendTag(new NBTTagString(name)); - NBTTagList listDate = new NBTTagList(); - for (String name : ServerCloneController.Instance.getClonesDate(tab)) - listDate.appendTag(new NBTTagString(name)); + + if (folder != null) { + ServerCloneController.Instance.removeClone(cloneName, folder); + for (String name : ServerCloneController.Instance.getClones(folder)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(folder)) + listDate.appendTag(new NBTTagString(name)); + } else { + ServerCloneController.Instance.removeClone(cloneName, tab); + for (String name : ServerCloneController.Instance.getClones(tab)) + list.appendTag(new NBTTagString(name)); + for (String name : ServerCloneController.Instance.getClonesDate(tab)) + listDate.appendTag(new NBTTagString(name)); + } NBTTagCompound compound = new NBTTagCompound(); compound.setTag("List", list); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java index 3a8abd9c0..2c66572e3 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneSavePacket.java @@ -25,6 +25,7 @@ public final class CloneSavePacket extends AbstractPacket { private String name; private int tab; + private String folderName; private NBTTagCompound tagExtra; private NBTTagCompound tagCompound; @@ -34,6 +35,15 @@ public final class CloneSavePacket extends AbstractPacket { public CloneSavePacket(String name, int tab, NBTTagCompound tagExtra, NBTTagCompound tagCompound) { this.name = name; this.tab = tab; + this.folderName = null; + this.tagExtra = tagExtra; + this.tagCompound = tagCompound; + } + + public CloneSavePacket(String name, String folderName, NBTTagCompound tagExtra, NBTTagCompound tagCompound) { + this.name = name; + this.tab = -1; + this.folderName = folderName; this.tagExtra = tagExtra; this.tagCompound = tagCompound; } @@ -58,6 +68,9 @@ public final class CloneSavePacket extends AbstractPacket { public void sendData(ByteBuf out) throws IOException { ByteBufUtils.writeString(out, this.name); out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } ByteBufUtils.writeNBT(out, this.tagExtra); ByteBufUtils.writeNBT(out, this.tagCompound); } @@ -75,11 +88,20 @@ public final class CloneSavePacket extends AbstractPacket { String name = ByteBufUtils.readString(in); int tab = in.readInt(); + String folder = null; + if (tab == -1) { + folder = ByteBufUtils.readString(in); + } NBTTagCompound tagExtra = ByteBufUtils.readNBT(in); NBTTagCompound tagCompound = ByteBufUtils.readNBT(in); NBTTagList tagList = tagCompound.getTagList("TagUUIDs", 8); data.cloned.setTag("TagUUIDs", tagList); - ServerCloneController.Instance.addClone(data.cloned, name, tab, tagExtra); + + if (folder != null) { + ServerCloneController.Instance.addClone(data.cloned, name, folder, tagExtra); + } else { + ServerCloneController.Instance.addClone(data.cloned, name, tab, tagExtra); + } } } diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java index 4d7b21aac..926c5519c 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/CloneTagListPacket.java @@ -13,6 +13,7 @@ import kamkeel.npcs.network.packets.data.large.GuiDataPacket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; +import kamkeel.npcs.util.ByteBufUtils; import noppes.npcs.controllers.ServerTagMapController; import noppes.npcs.controllers.data.TagMap; @@ -22,9 +23,16 @@ public final class CloneTagListPacket extends AbstractPacket { public static String packetName = "Request|CloneTagList"; private int tab; + private String folderName; public CloneTagListPacket(int tab) { this.tab = tab; + this.folderName = null; + } + + public CloneTagListPacket(String folderName) { + this.tab = -1; + this.folderName = folderName; } public CloneTagListPacket() { @@ -44,6 +52,9 @@ public final class CloneTagListPacket extends AbstractPacket { @Override public void sendData(ByteBuf out) throws IOException { out.writeInt(tab); + if (tab == -1) { + ByteBufUtils.writeString(out, folderName); + } } @Override @@ -54,7 +65,13 @@ public final class CloneTagListPacket extends AbstractPacket { return; int tab = in.readInt(); - TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); + TagMap tagMap; + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + tagMap = ServerTagMapController.Instance.getTagMap(folder); + } else { + tagMap = ServerTagMapController.Instance.getTagMap(tab); + } NBTTagCompound compound = new NBTTagCompound(); compound.setTag("CloneTags", tagMap.writeNBT()); GuiDataPacket.sendGuiData((EntityPlayerMP) player, compound); diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java index cc4dfb3ed..0ad817b06 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/MobSpawnerPacket.java @@ -31,6 +31,7 @@ public class MobSpawnerPacket extends AbstractPacket { private String selectedName; private int tab; + private String folderName; private NBTTagCompound compound; @@ -44,6 +45,17 @@ public class MobSpawnerPacket extends AbstractPacket { this.posz = posz; this.selectedName = selectedName; this.tab = tab; + this.folderName = null; + } + + public MobSpawnerPacket(Action type, int posX, int posY, int posz, String selectedName, String folderName) { + this.type = type; + this.posX = posX; + this.posY = posY; + this.posz = posz; + this.selectedName = selectedName; + this.tab = -1; + this.folderName = folderName; } public MobSpawnerPacket(Action type, int posX, int posY, int posz, NBTTagCompound compound) { @@ -58,6 +70,10 @@ public class MobSpawnerPacket extends AbstractPacket { PacketClient.sendClient(new MobSpawnerPacket(Action.Server, x, y, z, name, tab)); } + public static void ServerFolder(int x, int y, int z, String name, String folderName) { + PacketClient.sendClient(new MobSpawnerPacket(Action.Server, x, y, z, name, folderName)); + } + public static void Client(int x, int y, int z, NBTTagCompound compound) { PacketClient.sendClient(new MobSpawnerPacket(Action.Client, x, y, z, compound)); } @@ -88,6 +104,9 @@ public class MobSpawnerPacket extends AbstractPacket { if (type == Action.Server) { ByteBufUtils.writeString(out, this.selectedName); out.writeInt(this.tab); + if (this.tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } } else { ByteBufUtils.writeNBT(out, this.compound); } @@ -107,10 +126,18 @@ public class MobSpawnerPacket extends AbstractPacket { int z = in.readInt(); NBTTagCompound compound; - if (requestedAction == Action.Server) - compound = ServerCloneController.Instance.getCloneData(player, ByteBufUtils.readString(in), in.readInt()); - else + if (requestedAction == Action.Server) { + String name = ByteBufUtils.readString(in); + int tab = in.readInt(); + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + compound = ServerCloneController.Instance.getCloneData(player, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(player, name, tab); + } + } else { compound = ByteBufUtils.readNBT(in); + } if (!ConfigScript.canScript(player, CustomNpcsPermissions.SCRIPT)) { return; diff --git a/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java index b83fb9286..8afde02cf 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/clone/SpawnMobPacket.java @@ -37,6 +37,7 @@ public class SpawnMobPacket extends AbstractPacket { private String selectedName; private int tab; + private String folderName; private NBTTagCompound compound; @@ -50,6 +51,17 @@ public class SpawnMobPacket extends AbstractPacket { this.posz = posz; this.selectedName = selectedName; this.tab = tab; + this.folderName = null; + } + + public SpawnMobPacket(Action type, int posX, int posY, int posz, String selectedName, String folderName) { + this.type = type; + this.posX = posX; + this.posY = posY; + this.posz = posz; + this.selectedName = selectedName; + this.tab = -1; + this.folderName = folderName; } public SpawnMobPacket(Action type, int posX, int posY, int posz, NBTTagCompound compound) { @@ -64,6 +76,10 @@ public class SpawnMobPacket extends AbstractPacket { PacketClient.sendClient(new SpawnMobPacket(Action.Server, x, y, z, name, tab)); } + public static void ServerFolder(int x, int y, int z, String name, String folderName) { + PacketClient.sendClient(new SpawnMobPacket(Action.Server, x, y, z, name, folderName)); + } + public static void Client(int x, int y, int z, NBTTagCompound compound) { PacketClient.sendClient(new SpawnMobPacket(Action.Client, x, y, z, compound)); } @@ -94,6 +110,9 @@ public class SpawnMobPacket extends AbstractPacket { if (type == Action.Server) { ByteBufUtils.writeString(out, this.selectedName); out.writeInt(this.tab); + if (this.tab == -1) { + ByteBufUtils.writeString(out, this.folderName); + } } else { ByteBufUtils.writeNBT(out, this.compound); } @@ -113,10 +132,18 @@ public class SpawnMobPacket extends AbstractPacket { int z = in.readInt(); NBTTagCompound compound; - if (requestedAction == Action.Server) - compound = ServerCloneController.Instance.getCloneData(player, ByteBufUtils.readString(in), in.readInt()); - else + if (requestedAction == Action.Server) { + String name = ByteBufUtils.readString(in); + int tab = in.readInt(); + if (tab == -1) { + String folder = ByteBufUtils.readString(in); + compound = ServerCloneController.Instance.getCloneData(player, name, folder); + } else { + compound = ServerCloneController.Instance.getCloneData(player, name, tab); + } + } else { compound = ByteBufUtils.readNBT(in); + } if (compound == null) return; diff --git a/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java b/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java index 37383ea6c..d025fcb26 100644 --- a/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java +++ b/src/main/java/kamkeel/npcs/network/packets/request/script/ScriptFilesPacket.java @@ -13,6 +13,7 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcsPermissions; import noppes.npcs.NBTTags; +import noppes.npcs.client.ScriptClientConfig; import noppes.npcs.config.ConfigScript; import noppes.npcs.controllers.ScriptController; @@ -39,7 +40,7 @@ public final class ScriptFilesPacket extends AbstractPacket { @Override public PacketChannel getChannel() { - return PacketHandler.DATA_PACKET; + return PacketHandler.REQUEST_PACKET; } @Override @@ -47,7 +48,6 @@ public final class ScriptFilesPacket extends AbstractPacket { return CustomNpcsPermissions.SCRIPT_GLOBAL; } - @SideOnly(Side.CLIENT) @Override public void sendData(ByteBuf out) throws IOException { ByteBufUtils.writeNBT(out, getScriptsNbt(lang)); @@ -70,8 +70,8 @@ public final class ScriptFilesPacket extends AbstractPacket { } //Set client side configs - ConfigScript.ScriptingEnabled = compound.getBoolean("ScriptingEnabled"); - ConfigScript.RunLoadedScriptsFirst = compound.getBoolean("LoadedFirst"); + ScriptClientConfig.setScriptingEnabled(compound.getBoolean("ScriptingEnabled")); + ScriptClientConfig.setRunLoadedScriptsFirst(compound.getBoolean("LoadedFirst")); ScriptController.Instance.globalRevision = compound.getInteger("GlobalRevision"); } diff --git a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java index e095dc61b..5ee5936b1 100644 --- a/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java +++ b/src/main/java/kamkeel/npcs/util/AnchorPointHelper.java @@ -100,9 +100,12 @@ public class AnchorPointHelper { break; } - x += anchorX * scale; - y += anchorY * scale; - z += anchorZ * scale; + // Rotate offsets relative to entity's body yaw + // +X = entity's right, +Y = up, +Z = entity's forward + Vec3 rotatedOffset = rotateOffsetByYaw(anchorX * scale, anchorY * scale, anchorZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; return Vec3.createVectorHelper(x, y, z); } @@ -229,9 +232,8 @@ public class AnchorPointHelper { double blockZ = modelZ * MODEL_SCALE * scale; // Apply body yaw rotation - // Renderer uses glRotate(180 - yaw), so: cos(180-yaw) = -cos(yaw), sin(180-yaw) = sin(yaw) - // Y-axis rotation: x' = x*cos + z*sin, z' = -x*sin + z*cos - // Substituting: x' = -x*cos(yaw) + z*sin(yaw), z' = -x*sin(yaw) - z*cos(yaw) + // Renderer applies glRotatef(180 - yaw) then glScalef(-1, -1, 1). + // Combined transform: x' = mx*cos(yaw) + mz*sin(yaw), z' = mx*sin(yaw) - mz*cos(yaw) float bodyYaw = (float) Math.toRadians(entity.renderYawOffset); double cosYaw = Math.cos(bodyYaw); double sinYaw = Math.sin(bodyYaw); @@ -247,9 +249,11 @@ public class AnchorPointHelper { double worldY = entity.posY + shoulderHeight - blockY; double worldZ = entity.posZ + worldOffsetZ; - worldX += anchor.anchorOffsetX * scale; - worldY += anchor.anchorOffsetY * scale; - worldZ += anchor.anchorOffsetZ * scale; + // Rotate offsets relative to entity's body yaw + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + worldX += rotatedOffset.xCoord; + worldY += rotatedOffset.yCoord; + worldZ += rotatedOffset.zCoord; return Vec3.createVectorHelper(worldX, worldY, worldZ); } @@ -318,9 +322,11 @@ public class AnchorPointHelper { double y = entity.posY + entity.height * FALLBACK_ARM_HEIGHT + armLengthOffset; double z = entity.posZ + lateralZ + forwardZ; - x += anchor.anchorOffsetX * scale; - y += anchor.anchorOffsetY * scale; - z += anchor.anchorOffsetZ * scale; + // Rotate offsets relative to entity's body yaw + Vec3 rotatedOffset = rotateOffsetByYaw(anchor.anchorOffsetX * scale, anchor.anchorOffsetY * scale, anchor.anchorOffsetZ * scale, bodyYaw); + x += rotatedOffset.xCoord; + y += rotatedOffset.yCoord; + z += rotatedOffset.zCoord; return Vec3.createVectorHelper(x, y, z); } @@ -345,4 +351,17 @@ public class AnchorPointHelper { return FRONT_HEIGHT; } } + + /** + * Rotate an offset vector by the entity's body yaw so offsets are entity-relative. + * +X = entity's right, +Y = up, +Z = entity's forward. + * @param bodyYawRad body yaw in radians + */ + private static Vec3 rotateOffsetByYaw(double offsetX, double offsetY, double offsetZ, float bodyYawRad) { + double cos = Math.cos(bodyYawRad); + double sin = Math.sin(bodyYawRad); + double worldX = -offsetX * cos - offsetZ * sin; + double worldZ = -offsetX * sin + offsetZ * cos; + return Vec3.createVectorHelper(worldX, offsetY, worldZ); + } } diff --git a/src/main/java/kamkeel/npcs/util/BukkitUtil.java b/src/main/java/kamkeel/npcs/util/BukkitUtil.java index bc35cae6c..29f4a522f 100644 --- a/src/main/java/kamkeel/npcs/util/BukkitUtil.java +++ b/src/main/java/kamkeel/npcs/util/BukkitUtil.java @@ -33,6 +33,8 @@ public class BukkitUtil { private static Method getPluginManager; private static Method isPluginEnabled; + private static Method getPlugin; + /** * Initializes Bukkit integration using reflection. * Should be called during FMLServerStartedEvent to ensure Bukkit is fully loaded. @@ -63,6 +65,7 @@ public class BukkitUtil { Class pluginManagerClass = Class.forName("org.bukkit.plugin.PluginManager"); isPluginEnabled = pluginManagerClass.getMethod("isPluginEnabled", String.class); + getPlugin = pluginManagerClass.getMethod("getPlugin", String.class); bukkitEnabled = true; logger.info("Bukkit integration enabled"); @@ -95,7 +98,6 @@ public class BukkitUtil { /** * Checks if a specific Bukkit plugin is enabled. - * * @param pluginName the plugin name to check * @return true if the plugin is enabled */ @@ -113,7 +115,6 @@ public class BukkitUtil { /** * Gets a Bukkit OfflinePlayer by name. - * * @param playerName the player name * @return the OfflinePlayer object, or null if not available */ @@ -130,7 +131,6 @@ public class BukkitUtil { /** * Gets a Bukkit Player by name (online players only). - * * @param playerName the player name * @return the Player object, or null if not online or not available */ @@ -147,7 +147,6 @@ public class BukkitUtil { /** * Gets a service provider from Bukkit's ServicesManager. - * * @param serviceClass the service class to get * @return the service provider, or null if not available */ @@ -186,4 +185,13 @@ public class BukkitUtil { public static Class getPlayerClass() { return playerClass; } + + public static Object getPlugin(String plugin) { + try { + return getPlugin.invoke(getPluginManager.invoke(null), plugin); + } catch (Throwable ignored) { + + } + return null; + } } diff --git a/src/main/java/kamkeel/npcs/util/Register.java b/src/main/java/kamkeel/npcs/util/Register.java new file mode 100644 index 000000000..ff6b0f24e --- /dev/null +++ b/src/main/java/kamkeel/npcs/util/Register.java @@ -0,0 +1,131 @@ +package kamkeel.npcs.util; + +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; +import noppes.npcs.LogWriter; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.data.Animation; + +import java.util.*; +import java.util.function.Supplier; + +public class Register { + public static final Map> REGISTERED_NAMESPACES = new LinkedHashMap<>(); + public static final Map NAMESPACE_DISPLAY_NAMES = new LinkedHashMap<>(); + private final String registryKey; + protected final String namespace; + protected final Map> entries = new LinkedHashMap<>(); + + private Register(String registryKey, String namespace) { + this.registryKey = registryKey; + this.namespace = namespace; + } + + public T register(String factoryName, Supplier factory) { + entries.put(registryKey + "." + namespace + "." + factoryName, factory); + return factory.get(); + } + + public static boolean isEmpty(String registryKey) { + if (REGISTERED_NAMESPACES.isEmpty()) return true; + + List list = REGISTERED_NAMESPACES.get(registryKey); + if (list == null || list.isEmpty()) return true; + + return false; + } + + public List catalogue() { + List list = new ArrayList<>(); + for (String regKey : REGISTERED_NAMESPACES.keySet()) { + List nameSp = REGISTERED_NAMESPACES.get(regKey); + for (String name : nameSp) { + List nameSpContent = catalogue(regKey, name); + list.addAll(nameSpContent); + } + } + + return list; + } + + public List catalogue(String namespace) { + return catalogue(registryKey, namespace); + } + + public List catalogue(String registryKey, String namespace) { + List list = new ArrayList<>(); + for (Map.Entry> entry : entries.entrySet()) { + if (entry.getKey().startsWith(registryKey + "." + namespace + ":")) + list.add(entry.getValue().get()); + } + + return list; + } + + public static class Abilities extends Register { + private Abilities(String namespace) { + super("ability", namespace); + } + + public void register() { + for (Map.Entry> entry : entries.entrySet()) { + AbilityController.Instance.registerType(entry.getValue().get().getTypeId(), entry.getValue()); + } + } + + public static Register.Abilities create(String namespace, String displayName) { + if (!REGISTERED_NAMESPACES.containsKey("ability")) + REGISTERED_NAMESPACES.put("ability", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("ability").contains(namespace)) { + LogWriter.error("REGISTER ABILITIES: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("ability").add(namespace); + NAMESPACE_DISPLAY_NAMES.put(namespace, displayName); + + return new Register.Abilities(namespace); + } + } + + public static class Animations extends Register { + private final Class modClass; + private final String animationsPath; + + private Animations(Class modClass, String animationsPath, String namespace) { + super("animation", namespace); + this.animationsPath = animationsPath; + this.modClass = modClass; + } + + @Override + public Animation register(String factoryName, Supplier factory) { + return super.register(factoryName, factory); + } + + public void register() { + try { + String path = "/assets/" + namespace + "/" + animationsPath; + for (Map.Entry> entry : entries.entrySet()) { + String name = entry.getKey().substring(entry.getKey().indexOf(namespace + ".") + 1); + AnimationController.Instance.loadBuiltInAnimation(modClass, path, name); + } + } catch (Exception e) { + LogWriter.error("Error scanning built-in animations folder", e); + } + } + + public static Register.Animations create(Class modClass, String animationsPath, String namespace) { + if (!REGISTERED_NAMESPACES.containsKey("animation")) + REGISTERED_NAMESPACES.put("animation", new ArrayList<>()); + + if (REGISTERED_NAMESPACES.get("animation").contains(namespace)) { + LogWriter.error("REGISTER ANIMATIONS: Namespace " + namespace + " already registered!"); + } + + REGISTERED_NAMESPACES.get("animation").add(namespace); + + return new Register.Animations(modClass, animationsPath, namespace); + } + } +} diff --git a/src/main/java/kamkeel/npcs/util/VaultUtil.java b/src/main/java/kamkeel/npcs/util/VaultUtil.java index 64743ffba..c25ea3f3a 100644 --- a/src/main/java/kamkeel/npcs/util/VaultUtil.java +++ b/src/main/java/kamkeel/npcs/util/VaultUtil.java @@ -75,8 +75,12 @@ public class VaultUtil { } // Load Vault classes - economyClass = Class.forName("net.milkbowl.vault.economy.Economy"); - economyResponseClass = Class.forName("net.milkbowl.vault.economy.EconomyResponse"); + Object vault = BukkitUtil.getPlugin("Vault"); + if (vault == null) + return; + ClassLoader vaultLoader = vault.getClass().getClassLoader(); + economyClass = vaultLoader.loadClass("net.milkbowl.vault.economy.Economy"); + economyResponseClass = vaultLoader.loadClass("net.milkbowl.vault.economy.EconomyResponse"); // Get Economy methods (using deprecated String methods for broader compatibility) isEnabled = economyClass.getMethod("isEnabled"); @@ -174,7 +178,6 @@ public class VaultUtil { /** * Checks if a player has an account in the economy system. - * * @param player the player to check * @return true if the player has an account */ @@ -184,7 +187,6 @@ public class VaultUtil { /** * Checks if a player has an account in the economy system. - * * @param playerName the player name to check * @return true if the player has an account */ @@ -205,7 +207,6 @@ public class VaultUtil { /** * Gets the balance of a player. - * * @param player the player * @return the player's balance, or 0 if not available */ @@ -215,7 +216,6 @@ public class VaultUtil { /** * Gets the balance of a player by name. - * * @param playerName the player name * @return the player's balance, or 0 if not available */ @@ -236,7 +236,6 @@ public class VaultUtil { /** * Checks if a player has at least the specified amount. - * * @param player the player * @param amount the amount to check * @return true if the player has at least the specified amount @@ -247,9 +246,8 @@ public class VaultUtil { /** * Checks if a player has at least the specified amount. - * * @param playerName the player name - * @param amount the amount to check + * @param amount the amount to check * @return true if the player has at least the specified amount */ public static boolean has(String playerName, double amount) { @@ -269,7 +267,6 @@ public class VaultUtil { /** * Withdraws money from a player's account. - * * @param player the player * @param amount the amount to withdraw * @return true if the transaction was successful @@ -280,9 +277,8 @@ public class VaultUtil { /** * Withdraws money from a player's account. - * * @param playerName the player name - * @param amount the amount to withdraw + * @param amount the amount to withdraw * @return true if the transaction was successful */ public static boolean withdrawMoney(String playerName, double amount) { @@ -305,7 +301,6 @@ public class VaultUtil { /** * Adds money to a player's account (deposit). - * * @param player the player * @param amount the amount to add * @return true if the transaction was successful @@ -316,9 +311,8 @@ public class VaultUtil { /** * Adds money to a player's account (deposit). - * * @param playerName the player name - * @param amount the amount to add + * @param amount the amount to add * @return true if the transaction was successful */ public static boolean addMoney(String playerName, double amount) { @@ -342,7 +336,6 @@ public class VaultUtil { /** * Sets a player's balance to the specified amount. * This withdraws all money first, then deposits the new amount. - * * @param player the player * @param amount the new balance * @return true if the transaction was successful @@ -354,9 +347,8 @@ public class VaultUtil { /** * Sets a player's balance to the specified amount. * This withdraws all money first, then deposits the new amount. - * * @param playerName the player name - * @param amount the new balance + * @param amount the new balance * @return true if the transaction was successful */ public static boolean setBalance(String playerName, double amount) { @@ -376,7 +368,6 @@ public class VaultUtil { /** * Formats an amount according to the economy plugin's settings. - * * @param amount the amount to format * @return the formatted string, or the raw number as string if not available */ @@ -393,7 +384,6 @@ public class VaultUtil { /** * Gets the plural currency name (e.g., "Dollars"). - * * @return the plural currency name, or "coins" if not available */ public static String getCurrencyNamePlural() { @@ -409,7 +399,6 @@ public class VaultUtil { /** * Gets the singular currency name (e.g., "Dollar"). - * * @return the singular currency name, or "coin" if not available */ public static String getCurrencyNameSingular() { @@ -425,7 +414,6 @@ public class VaultUtil { /** * Creates an account for the player if one doesn't exist. - * * @param player the player * @return true if the account was created or already exists */ @@ -435,7 +423,6 @@ public class VaultUtil { /** * Creates an account for the player if one doesn't exist. - * * @param playerName the player name * @return true if the account was created or already exists */ @@ -472,7 +459,6 @@ public class VaultUtil { /** * Gets a list of all bank names. - * * @return list of bank names, or empty list if not available */ @SuppressWarnings("unchecked") @@ -489,7 +475,6 @@ public class VaultUtil { /** * Gets the balance of a bank. - * * @param bankName the bank name * @return the bank balance, or 0 if not available */ @@ -507,9 +492,8 @@ public class VaultUtil { /** * Checks if a bank has at least the specified amount. - * * @param bankName the bank name - * @param amount the amount to check + * @param amount the amount to check * @return true if the bank has at least the specified amount */ public static boolean bankHas(String bankName, double amount) { @@ -526,9 +510,8 @@ public class VaultUtil { /** * Withdraws money from a bank. - * * @param bankName the bank name - * @param amount the amount to withdraw + * @param amount the amount to withdraw * @return true if the transaction was successful */ public static boolean bankWithdraw(String bankName, double amount) { @@ -545,9 +528,8 @@ public class VaultUtil { /** * Deposits money into a bank. - * * @param bankName the bank name - * @param amount the amount to deposit + * @param amount the amount to deposit * @return true if the transaction was successful */ public static boolean bankDeposit(String bankName, double amount) { @@ -564,9 +546,8 @@ public class VaultUtil { /** * Transfers money from one player to another. - * - * @param from the player to take money from - * @param to the player to give money to + * @param from the player to take money from + * @param to the player to give money to * @param amount the amount to transfer * @return true if the transfer was successful */ @@ -576,10 +557,9 @@ public class VaultUtil { /** * Transfers money from one player to another. - * * @param fromPlayerName the player name to take money from - * @param toPlayerName the player name to give money to - * @param amount the amount to transfer + * @param toPlayerName the player name to give money to + * @param amount the amount to transfer * @return true if the transfer was successful */ public static boolean transfer(String fromPlayerName, String toPlayerName, double amount) { diff --git a/src/main/java/noppes/npcs/CommonProxy.java b/src/main/java/noppes/npcs/CommonProxy.java index 6fefe01c1..ee65ad6a5 100644 --- a/src/main/java/noppes/npcs/CommonProxy.java +++ b/src/main/java/noppes/npcs/CommonProxy.java @@ -43,6 +43,7 @@ import noppes.npcs.containers.ContainerNpcQuestReward; import noppes.npcs.containers.ContainerNpcQuestTypeItem; import noppes.npcs.controllers.data.AnimationData; import noppes.npcs.controllers.data.PlayerData; +import noppes.npcs.config.ConfigScript; import noppes.npcs.entity.EntityNPCInterface; public class CommonProxy implements IGuiHandler { @@ -220,4 +221,24 @@ public class CommonProxy implements IGuiHandler { public void buildPackageIndex() { } + + public boolean isScriptingEnabled() { + return ConfigScript.ScriptingEnabled; + } + + public boolean isRunLoadedScriptsFirst() { + return ConfigScript.RunLoadedScriptsFirst; + } + + public boolean isGlobalPlayerScripts() { + return ConfigScript.GlobalPlayerScripts; + } + + public boolean isGlobalForgeScripts() { + return ConfigScript.GlobalForgeScripts; + } + + public boolean isGlobalNPCScripts() { + return ConfigScript.GlobalNPCScripts; + } } diff --git a/src/main/java/noppes/npcs/CustomNpcs.java b/src/main/java/noppes/npcs/CustomNpcs.java index ff4617545..0bc081429 100644 --- a/src/main/java/noppes/npcs/CustomNpcs.java +++ b/src/main/java/noppes/npcs/CustomNpcs.java @@ -158,7 +158,13 @@ public class CustomNpcs { @SideOnly(Side.CLIENT) private static IDynamicCompiler clientJaninoCompiler; @SideOnly(Side.CLIENT) - private final static Set> clientClassFilterConsumer = new HashSet<>(); + private static Set> clientClassFilterConsumer; + + static { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + clientClassFilterConsumer = new HashSet<>(); + } + } @SideOnly(Side.CLIENT) public static void addClassesToClientClassFilter(Consumer consumer) { diff --git a/src/main/java/noppes/npcs/CustomNpcsPermissions.java b/src/main/java/noppes/npcs/CustomNpcsPermissions.java index 5e7c2924e..af9b2b9af 100644 --- a/src/main/java/noppes/npcs/CustomNpcsPermissions.java +++ b/src/main/java/noppes/npcs/CustomNpcsPermissions.java @@ -66,8 +66,8 @@ 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_ABILITY = new Permission("customnpcs.global.ability"); public static final Permission GLOBAL_EFFECT = new Permission("customnpcs.global.effect"); public static final Permission SPAWNER_MOB = new Permission("customnpcs.spawner.mob"); @@ -111,9 +111,6 @@ 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 Method hasPermission; diff --git a/src/main/java/noppes/npcs/DataAbilities.java b/src/main/java/noppes/npcs/DataAbilities.java index 8c44c482e..5e1ff694f 100644 --- a/src/main/java/noppes/npcs/DataAbilities.java +++ b/src/main/java/noppes/npcs/DataAbilities.java @@ -18,6 +18,7 @@ import noppes.npcs.entity.EntityNPCInterface; import noppes.npcs.scripted.NpcAPI; import noppes.npcs.scripted.event.AbilityEvent; + import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -43,7 +44,7 @@ public class DataAbilities { /** * Whether the ability system is enabled for this NPC */ - public boolean enabled = false; + public boolean enabled = true; /** * Minimum cooldown ticks between abilities (global minimum) @@ -89,6 +90,24 @@ public class DataAbilities { private transient float lockedRenderYawOffset = 0; private transient float lockedPitch = 0; + /** + * Locked position values for movement lock. + * Stored when entering a locked phase, applied after super.onLivingUpdate() + * to override any position changes from AI/physics. + */ + private transient boolean positionLocked = false; + private transient double lockedPosX = 0; + private transient double lockedPosY = 0; + private transient double lockedPosZ = 0; + + /** + * Hit scan state - forces NPC to face target. + * Set during tickCurrentAbility(), applied after super.onLivingUpdate() + * to override AI look helper rotation. + */ + private transient boolean hitScanActive = false; + private transient EntityLivingBase hitScanTarget = null; + // ═══════════════════════════════════════════════════════════════════ // CONSTRUCTOR // ═══════════════════════════════════════════════════════════════════ @@ -106,10 +125,33 @@ public class DataAbilities { * Should be called every tick from onLivingUpdate(). */ public void tick() { - if (!enabled || npc.worldObj.isRemote || npc.isKilled()) { + if (npc.worldObj.isRemote) { return; } + // Force-stop any running ability when NPC is killed or abilities are disabled + if (!enabled || npc.isKilled()) { + if (currentAbility != null) { + removeTelegraph(currentAbility); + stopAbilityAnimation(); + releaseRotationControl(); + releaseLockedPosition(); + currentAbility = null; + lastTarget = null; + } else { + // No ability but locks could be orphaned + if (rotationLocked || hitScanActive) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + return; + } + + // Safety: release orphaned locks if no ability is actively executing + if (currentAbility == null || !currentAbility.isExecuting()) { + if (rotationLocked || hitScanActive) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + } + // Tick current ability if executing if (currentAbility != null && currentAbility.isExecuting()) { tickCurrentAbility(); @@ -132,11 +174,23 @@ public class DataAbilities { // Handle phase-specific logic switch (currentAbility.getPhase()) { case WINDUP: + if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) { + // Burst replay: re-enter windup - set up telegraph, sound, animation, locks + if (currentAbility.isRotationLockedDuringWindup()) { + captureLockedRotation(); + } + if (currentAbility.isMovementLockedDuringWindup() && !currentAbility.hasAbilityMovement()) { + captureLockedPosition(); + } + spawnTelegraph(currentAbility, target); + playAbilitySound(currentAbility.getWindUpSound()); + playAbilityAnimation(currentAbility.getWindUpAnimation()); + } currentAbility.onWindUpTick(npc, target, npc.worldObj, currentAbility.getCurrentTick()); break; case ACTIVE: - if (phaseChanged && oldPhase == AbilityPhase.WINDUP) { + if (phaseChanged && (oldPhase == AbilityPhase.WINDUP || oldPhase == AbilityPhase.BURST_DELAY)) { // Just entered ACTIVE phase - lock telegraph position if it was following // This commits the ability to its current target position TelegraphInstance telegraph = currentAbility.getTelegraphInstance(); @@ -147,16 +201,38 @@ 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(); + // Handle rotation control transition from WINDUP to ACTIVE + if (currentAbility.isRotationLockedDuringActive()) { + if (!rotationLocked) { + captureLockedRotation(); + } + } else if (rotationLocked) { + releaseRotationControl(); + } + + // Handle position lock transition from WINDUP to ACTIVE + if (currentAbility.isMovementLockedDuringActive() && !currentAbility.hasAbilityMovement()) { + if (!positionLocked) { + captureLockedPosition(); + } + } else if (positionLocked) { + releaseLockedPosition(); + } + + // Burst re-fire without replay: let entity-spawning abilities spawn+fire in one step + if (oldPhase == AbilityPhase.BURST_DELAY && !currentAbility.isBurstReplayAnimations()) { + currentAbility.onBurstRefire(npc, target, npc.worldObj); } // Play active sound and animation playAbilitySound(currentAbility.getActiveSound()); playAbilityAnimation(currentAbility.getActiveAnimation()); + // Snap NPC to face target before execute so startMoving() reads correct rotation + if (currentAbility.isHitScanForCurrentPhase() && target != null) { + faceTarget(target); + } + // Fire execute event (cancelable) AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent( npc.wrappedNPC, currentAbility, target); @@ -181,6 +257,31 @@ public class DataAbilities { handleAbilityCompletion(target); return; } + + // Auto-complete for burst overlap mode (entities fly independently) + // This allows entity-spawning abilities to immediately chain next burst + // without each type needing to check burst state in their onActiveTick() + // Wait until all staggered projectiles have been fired before auto-completing + if (currentAbility.isBurstEnabled() && currentAbility.isBurstOverlap() + && currentAbility.getBurstIndex() < currentAbility.getBurstAmount() + && currentAbility.getPhase() == AbilityPhase.ACTIVE + && currentAbility.isReadyForBurstCompletion(currentAbility.getCurrentTick())) { + currentAbility.signalCompletion(); + } + + // Check if ability entered burst delay during onActiveTick or overlap auto-complete + if (currentAbility.getPhase() == AbilityPhase.BURST_DELAY) { + // Release all locks - free movement/rotation during delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); + if (hitScanActive) releaseRotationControl(); + } + break; + + case BURST_DELAY: + // Free movement and rotation during burst delay + if (rotationLocked) releaseRotationControl(); + if (positionLocked) releaseLockedPosition(); break; case DAZED: @@ -193,6 +294,15 @@ public class DataAbilities { break; } + // Update hit scan state - actual facing is deferred to applyRotationControl() + // which runs AFTER super.onLivingUpdate() to override AI look helper + if (currentAbility != null && currentAbility.isExecuting() + && currentAbility.isHitScanForCurrentPhase() && target != null) { + enableHitScan(target); + } else if (hitScanActive) { + releaseRotationControl(); + } + // Apply movement control if ability is still executing if (currentAbility != null && currentAbility.isExecuting()) { applyMovementControl(); @@ -237,8 +347,9 @@ public class DataAbilities { npc.wrappedNPC, currentAbility, target); NpcAPI.EVENT_BUS.post(completeEvent); - // Release rotation lock before cleanup - releaseLockedRotation(); + // Release locks before cleanup + releaseRotationControl(); + releaseLockedPosition(); // Clean up and roll cooldown (this sets currentAbility to null) onAbilityComplete(); @@ -253,8 +364,9 @@ public class DataAbilities { // Stop any ability animation stopAbilityAnimation(); - // Release rotation lock - releaseLockedRotation(); + // Release locks + releaseRotationControl(); + releaseLockedPosition(); // Calculate cooldown: random(min, max) + ability offset int abilityCooldownOffset = currentAbility.getCooldownTicks(); @@ -343,6 +455,11 @@ public class DataAbilities { * Check if a specific ability is eligible for use. */ private boolean isAbilityEligible(Ability ability, EntityLivingBase target) { + // Check UserType allows NPCs + if (!ability.getAllowedBy().allowsNpc()) { + return false; + } + // Check enabled if (!ability.isEnabled()) { return false; @@ -385,18 +502,58 @@ public class DataAbilities { lastTarget = target; ability.start(target); - // Spawn telegraph and send to clients - spawnTelegraph(ability, target); - - // Play wind up sound if configured - playAbilitySound(ability.getWindUpSound()); - - // Play wind up animation if configured - playAbilityAnimation(ability.getWindUpAnimation()); + if (ability.getPhase() == AbilityPhase.ACTIVE) { + // Windup was 0 — skip telegraph/windup and go straight to active + executeImmediate(ability, target); + } else { + // Normal windup flow + if (ability.isRotationLockedDuringWindup()) { + captureLockedRotation(); + } + if (ability.isMovementLockedDuringWindup() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } + spawnTelegraph(ability, target); + playAbilitySound(ability.getWindUpSound()); + playAbilityAnimation(ability.getWindUpAnimation()); + } return true; } + /** + * Execute an ability immediately (no windup). + * Called when windUpTicks is 0. + */ + private void executeImmediate(Ability ability, EntityLivingBase target) { + // Lock rotation if rotation is locked during ACTIVE phase + if (ability.isRotationLockedDuringActive()) { + captureLockedRotation(); + } + if (ability.isMovementLockedDuringActive() && !ability.hasAbilityMovement()) { + captureLockedPosition(); + } + + // Play active sound and animation + playAbilitySound(ability.getActiveSound()); + playAbilityAnimation(ability.getActiveAnimation()); + + // Fire execute event (cancelable) + AbilityEvent.ExecuteEvent executeEvent = new AbilityEvent.ExecuteEvent( + npc.wrappedNPC, ability, target); + if (NpcAPI.EVENT_BUS.post(executeEvent)) { + return; + } + + // Call onExecute + ability.onExecute(npc, target, npc.worldObj); + + // Check if ability completed during onExecute + if (ability.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(target); + } + } + /** * Play a sound at the NPC's location. */ @@ -429,6 +586,14 @@ public class DataAbilities { playAbilityAnimation((Animation) AnimationController.Instance.get(animation)); } + public void playAbilityAnimation(String animation) { + if (animation.isEmpty()) return; + if (AnimationController.Instance == null) return; + if (AnimationController.Instance.get(animation, true) == null) return; + + playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true)); + } + /** * Stop any currently playing ability animation. */ @@ -501,18 +666,12 @@ 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; } + currentAbility.onDamageTaken(npc, (EntityLivingBase) source.getEntity(), source, amount); + if (currentAbility.canInterrupt(source)) { interruptCurrentAbility(source, amount); return true; @@ -583,8 +742,9 @@ public class DataAbilities { // Stop any ability animation stopAbilityAnimation(); - // Release rotation lock - releaseLockedRotation(); + // Release locks + releaseRotationControl(); + releaseLockedPosition(); // Fire interrupt event AbilityEvent.InterruptEvent interruptEvent = new AbilityEvent.InterruptEvent( @@ -606,7 +766,8 @@ public class DataAbilities { if (currentAbility != null) { removeTelegraph(currentAbility); stopAbilityAnimation(); - releaseLockedRotation(); + releaseRotationControl(); + releaseLockedPosition(); currentAbility.interrupt(); currentAbility = null; lastTarget = null; @@ -626,6 +787,11 @@ public class DataAbilities { return false; } + // Check UserType allows NPCs + if (!ability.getAllowedBy().allowsNpc()) { + return false; + } + // Stop any currently executing ability stopCurrentAbility(); @@ -898,12 +1064,15 @@ public class DataAbilities { } // ═══════════════════════════════════════════════════════════════════ - // ROTATION LOCKING + // ROTATION CONTROL // ═══════════════════════════════════════════════════════════════════ + /** Bit flag for rotation control (LOCKED or TRACK) in data watcher slot 15 */ + private static final int ROTATION_CONTROLLED_FLAG = 16; + /** * Capture current rotation values to lock NPC's look direction. - * Called when entering ACTIVE phase with movement locked during active. + * Called when entering a LOCKED rotation phase. */ private void captureLockedRotation() { lockedYaw = npc.rotationYaw; @@ -911,44 +1080,170 @@ public class DataAbilities { lockedRenderYawOffset = npc.renderYawOffset; lockedPitch = npc.rotationPitch; rotationLocked = true; + npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); } /** - * Release the rotation lock. - * Called when leaving ACTIVE phase or ability completes. + * Release rotation control (both locked and hit scan). */ - private void releaseLockedRotation() { + private void releaseRotationControl() { rotationLocked = false; + hitScanActive = false; + hitScanTarget = null; + npc.setBoolFlag(false, ROTATION_CONTROLLED_FLAG); } /** - * 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. + * Enable hit scan tracking for the given target. */ - public void applyLockedRotation() { - if (!rotationLocked) { + private void enableHitScan(EntityLivingBase target) { + if (!hitScanActive) { + hitScanActive = true; + npc.setBoolFlag(true, ROTATION_CONTROLLED_FLAG); + } + hitScanTarget = target; + } + + /** + * Snap the NPC to face the target instantly. + */ + private void faceTarget(EntityLivingBase target) { + double dx = target.posX - npc.posX; + double dz = target.posZ - npc.posZ; + double dy = (target.posY + target.getEyeHeight() * 0.5) - (npc.posY + npc.getEyeHeight()); + double distXZ = Math.sqrt(dx * dx + dz * dz); + + float yaw = (float) (Math.atan2(-dx, dz) * 180.0 / Math.PI); + float pitch = (float) (-(Math.atan2(dy, distXZ)) * 180.0 / Math.PI); + + npc.rotationYaw = yaw; + npc.rotationYawHead = yaw; + npc.renderYawOffset = yaw; + npc.rotationPitch = pitch; + npc.prevRotationYaw = yaw; + npc.prevRotationYawHead = yaw; + npc.prevRenderYawOffset = yaw; + npc.prevRotationPitch = pitch; + } + + /** + * Apply rotation control after super.onLivingUpdate() and super.onUpdate(). + * Handles both LOCKED (freeze at captured values) and TRACK (face target) modes. + * + * Server: computes the correct rotation (locked values or target facing). + * Client: trusts the server-synced rotation values and prevents body smoothing override. + */ + public void applyRotationControl() { + if (npc.worldObj.isRemote) { + // Client: check single flag for any rotation control + if (!npc.getBoolFlag(ROTATION_CONTROLLED_FLAG)) { + rotationLocked = false; + return; + } + // Trust server rotation, prevent body smoothing from overriding + npc.prevRotationYaw = npc.rotationYaw; + npc.prevRotationYawHead = npc.rotationYawHead; + npc.renderYawOffset = npc.rotationYawHead; + npc.prevRenderYawOffset = npc.rotationYawHead; + npc.prevRotationPitch = npc.rotationPitch; 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; + // Server: apply the appropriate rotation + if (hitScanActive && hitScanTarget != null && !hitScanTarget.isDead) { + faceTarget(hitScanTarget); + } else if (rotationLocked) { + npc.rotationYaw = lockedYaw; + npc.rotationYawHead = lockedYawHead; + npc.renderYawOffset = lockedRenderYawOffset; + npc.rotationPitch = lockedPitch; + npc.prevRotationYaw = lockedYaw; + npc.prevRotationYawHead = lockedYawHead; + npc.prevRenderYawOffset = lockedRenderYawOffset; + npc.prevRotationPitch = lockedPitch; + } } /** - * Check if rotation is currently locked. + * Check if rotation is currently controlled (locked or tracking target). + * Used by AI tasks to determine if they should try to change NPC look direction. */ public boolean isRotationLocked() { - return rotationLocked; + return rotationLocked || hitScanActive; + } + + // ═══════════════════════════════════════════════════════════════════ + // POSITION LOCKING + // ═══════════════════════════════════════════════════════════════════ + + /** Bit flag for position lock in data watcher slot 15 */ + private static final int POSITION_LOCKED_FLAG = 32; + + /** + * Capture current position to lock NPC in place. + * Called when entering a phase with movement lock. + */ + private void captureLockedPosition() { + lockedPosX = npc.posX; + lockedPosY = npc.posY; + lockedPosZ = npc.posZ; + positionLocked = true; + npc.setBoolFlag(true, POSITION_LOCKED_FLAG); + } + + /** + * Release the position lock. + * Called when leaving the locked phase or ability completes. + */ + private void releaseLockedPosition() { + positionLocked = false; + npc.setBoolFlag(false, POSITION_LOCKED_FLAG); + } + + /** + * Apply locked position values to the NPC. + * Called AFTER super.onLivingUpdate() in EntityNPCInterface to override + * any position changes from AI pathfinding, physics, or entity collisions. + * Runs on both client and server. + */ + public void applyLockedPosition() { + if (npc.worldObj.isRemote) { + // Client-side: check flag via data watcher + boolean flagActive = npc.getBoolFlag(POSITION_LOCKED_FLAG); + if (!flagActive) { + positionLocked = false; + return; + } + // First tick the flag is active: capture current position + if (!positionLocked) { + lockedPosX = npc.posX; + lockedPosY = npc.posY; + lockedPosZ = npc.posZ; + positionLocked = true; + } + // Snap position back and set prev to prevent interpolation jitter + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; + return; + } + + // Server-side: use stored locked values + if (!positionLocked) { + return; + } + + npc.setPosition(lockedPosX, lockedPosY, lockedPosZ); + npc.prevPosX = lockedPosX; + npc.prevPosY = lockedPosY; + npc.prevPosZ = lockedPosZ; + npc.motionX = 0; + npc.motionY = 0; + npc.motionZ = 0; } // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/NoppesUtilServer.java b/src/main/java/noppes/npcs/NoppesUtilServer.java index 684222526..b076d9484 100644 --- a/src/main/java/noppes/npcs/NoppesUtilServer.java +++ b/src/main/java/noppes/npcs/NoppesUtilServer.java @@ -2,6 +2,8 @@ package noppes.npcs; import io.netty.buffer.ByteBuf; import kamkeel.npcs.controllers.SyncController; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.packets.data.ParticlePacket; import kamkeel.npcs.network.packets.data.PlayerDataInfoPacket; @@ -748,7 +750,7 @@ public class NoppesUtilServer { public static void sendAbilityTypesInfo(EntityPlayerMP player) { HashMap map = new HashMap(); - kamkeel.npcs.controllers.data.ability.AbilityController controller = kamkeel.npcs.controllers.data.ability.AbilityController.Instance; + AbilityController controller = AbilityController.Instance; if (controller != null) { int index = 0; for (String typeId : controller.getTypes()) { @@ -764,6 +766,9 @@ public class NoppesUtilServer { if (controller != null) { int index = 0; for (String uuid : controller.getCustomAbilityIds()) { + Ability ability = controller.getCustomAbility(uuid); + if (ability == null || !ability.getAllowedBy().allowsNpc()) continue; + String name = controller.getCustomAbilityName(uuid); if (name == null || name.isEmpty()) name = uuid; map.put(name + "\t" + uuid, index++); diff --git a/src/main/java/noppes/npcs/ai/CombatHandler.java b/src/main/java/noppes/npcs/ai/CombatHandler.java index 750725551..ff81e4821 100644 --- a/src/main/java/noppes/npcs/ai/CombatHandler.java +++ b/src/main/java/noppes/npcs/ai/CombatHandler.java @@ -1,6 +1,7 @@ package noppes.npcs.ai; import kamkeel.npcs.addon.DBCAddon; +import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -80,13 +81,14 @@ public class CombatHandler { } // Handle guard counter before interruption - if (npc.abilities.getCurrentAbility() instanceof kamkeel.npcs.controllers.data.ability.type.AbilityGuard) { - kamkeel.npcs.controllers.data.ability.type.AbilityGuard guard = - (kamkeel.npcs.controllers.data.ability.type.AbilityGuard) npc.abilities.getCurrentAbility(); - if (guard.isGuarding() && e instanceof EntityLivingBase) { - guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount); - } - } + +// if (npc.abilities.getCurrentAbility() instanceof AbilityGuard) { +// AbilityGuard guard = +// (AbilityGuard) npc.abilities.getCurrentAbility(); +// if (guard.isGuarding() && e instanceof EntityLivingBase) { +// guard.onDamageTaken(npc, (EntityLivingBase) e, source, damageAmount); +// } +// } // Check for ability interruption npc.abilities.onDamage(source, damageAmount); diff --git a/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java b/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java index 4ee229b0e..3ba29ecd1 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIAmbushTarget.java @@ -93,7 +93,9 @@ public class EntityAIAmbushTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!this.theEntity.abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } } private Vec3 findHidingSpot() { diff --git a/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java b/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java index 5fe559fc2..473c0bfb8 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIAttackTarget.java @@ -118,7 +118,9 @@ public class EntityAIAttackTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F); + if (!this.npc.abilities.isRotationLocked()) { + this.npc.getLookHelper().setLookPositionWithEntity(this.entityTarget, 30.0F, 30.0F); + } // Skip pathfinding updates if ability is controlling movement if (!navOverride && !this.npc.abilities.isAbilityControllingMovement() && --this.field_75445_i <= 0) { diff --git a/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java b/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java index ef7b3f5ac..b07b911f4 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java +++ b/src/main/java/noppes/npcs/ai/EntityAIDodgeShoot.java @@ -63,7 +63,7 @@ public class EntityAIDodgeShoot extends EntityAIBase { * Updates the task */ public void updateTask() { - if (this.entity.getAttackTarget() != null) + if (this.entity.getAttackTarget() != null && !this.entity.abilities.isRotationLocked()) this.entity.getLookHelper().setLookPositionWithEntity(this.entity.getAttackTarget(), 30.0F, 30.0F); } } diff --git a/src/main/java/noppes/npcs/ai/EntityAIFollow.java b/src/main/java/noppes/npcs/ai/EntityAIFollow.java index 61cabd38f..f236c0727 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIFollow.java +++ b/src/main/java/noppes/npcs/ai/EntityAIFollow.java @@ -55,7 +55,9 @@ public class EntityAIFollow extends EntityAIBase { if (updateTick < 10) return; updateTick = 0; - this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed()); + if (!this.npc.abilities.isRotationLocked()) { + this.npc.getLookHelper().setLookPositionWithEntity(owner, 10.0F, (float) this.npc.getVerticalFaceSpeed()); + } double speed = 1 + distance / 150; if (speed > 3) diff --git a/src/main/java/noppes/npcs/ai/EntityAILook.java b/src/main/java/noppes/npcs/ai/EntityAILook.java index 3448fc4ed..b9474a60c 100644 --- a/src/main/java/noppes/npcs/ai/EntityAILook.java +++ b/src/main/java/noppes/npcs/ai/EntityAILook.java @@ -26,7 +26,7 @@ public class EntityAILook extends EntityAIBase { */ @Override public boolean shouldExecute() { - return !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive(); + return !npc.abilities.isRotationLocked() && !npc.isAttacking() && npc.getNavigator().noPath() && !npc.isPlayerSleeping() && npc.isEntityAlive(); } /** diff --git a/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java b/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java index 4c72ec278..0a9532261 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIOrbitTarget.java @@ -91,7 +91,9 @@ public class EntityAIOrbitTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!this.theEntity.abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } if (this.theEntity.getNavigator().noPath() && this.tick >= 0) { if (this.theEntity.onGround && !this.theEntity.isInWater()) { double d0 = this.targetDistance * (double) (MathHelper.cos(angle / 180.0F * (float) Math.PI)); diff --git a/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java b/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java index af88ac905..5e8fa6ec0 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java +++ b/src/main/java/noppes/npcs/ai/EntityAIRangedAttack.java @@ -100,7 +100,9 @@ public class EntityAIRangedAttack extends EntityAIBase { * Updates the task */ public void updateTask() { - this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F); + if (!this.entityHost.abilities.isRotationLocked()) { + this.entityHost.getLookHelper().setLookPositionWithEntity(this.attackTarget, 30.0F, 30.0F); + } double var1 = this.entityHost.getDistanceSq(this.attackTarget.posX, this.attackTarget.boundingBox.minY, this.attackTarget.posZ); float field_82642_h = this.entityHost.stats.rangedRange * this.entityHost.stats.rangedRange; diff --git a/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java b/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java index 1b64a12b7..8adad1ee2 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIStalkTarget.java @@ -68,7 +68,9 @@ public class EntityAIStalkTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!this.theEntity.abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } if (this.theEntity.getNavigator().noPath() || this.overRide) { if (this.isLookingAway()) { diff --git a/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java b/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java index d30ae3183..159c38fc9 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java +++ b/src/main/java/noppes/npcs/ai/EntityAIWatchClosest.java @@ -31,7 +31,7 @@ public class EntityAIWatchClosest extends EntityAIBase { */ @Override public boolean shouldExecute() { - if (this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) { + if (this.theWatcher.abilities.isRotationLocked() || this.theWatcher.getRNG().nextFloat() >= this.field_75331_e || theWatcher.isInteracting()) { return false; } else { if (this.theWatcher.getAttackTarget() != null) { diff --git a/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java b/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java index 3e91cc84b..e99d31ca2 100644 --- a/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java +++ b/src/main/java/noppes/npcs/ai/EntityAIZigZagTarget.java @@ -8,6 +8,7 @@ import net.minecraft.pathfinding.PathPoint; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import noppes.npcs.constants.AiMutex; +import noppes.npcs.entity.EntityNPCInterface; public class EntityAIZigZagTarget extends EntityAIBase { private EntityCreature theEntity; @@ -82,6 +83,8 @@ public class EntityAIZigZagTarget extends EntityAIBase { * Updates the task */ public void updateTask() { - this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + if (!(this.theEntity instanceof EntityNPCInterface) || !((EntityNPCInterface) this.theEntity).abilities.isRotationLocked()) { + this.theEntity.getLookHelper().setLookPositionWithEntity(targetEntity, 30.0F, 30.0F); + } } } diff --git a/src/main/java/noppes/npcs/client/ClientEventHandler.java b/src/main/java/noppes/npcs/client/ClientEventHandler.java index 7a839fbb5..a7a0f2b39 100644 --- a/src/main/java/noppes/npcs/client/ClientEventHandler.java +++ b/src/main/java/noppes/npcs/client/ClientEventHandler.java @@ -19,6 +19,8 @@ import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderHandEvent; import net.minecraftforge.client.event.RenderLivingEvent; import net.minecraftforge.client.event.RenderPlayerEvent; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; +import noppes.npcs.client.gui.player.AuctionTooltipHandler; import noppes.npcs.client.gui.customoverlay.OverlayCustom; import noppes.npcs.client.gui.hud.ClientHudManager; import noppes.npcs.client.gui.hud.CompassHudComponent; @@ -75,6 +77,11 @@ public class ClientEventHandler { } } + @SubscribeEvent + public void onItemTooltip(ItemTooltipEvent event) { + AuctionTooltipHandler.onItemTooltip(event); + } + @SubscribeEvent public void onMouse(MouseEvent event) { if (Minecraft.getMinecraft().currentScreen != null) diff --git a/src/main/java/noppes/npcs/client/ClientProxy.java b/src/main/java/noppes/npcs/client/ClientProxy.java index f43000c5b..88b113e44 100644 --- a/src/main/java/noppes/npcs/client/ClientProxy.java +++ b/src/main/java/noppes/npcs/client/ClientProxy.java @@ -76,6 +76,7 @@ import noppes.npcs.client.gui.GuiBorderBlock; import noppes.npcs.client.gui.GuiMerchantAdd; import noppes.npcs.client.gui.GuiNpcDimension; import noppes.npcs.client.gui.GuiNpcMobSpawner; +import noppes.npcs.client.gui.GuiNpcMobSpawnerFullscreen; import noppes.npcs.client.gui.GuiNpcMobSpawnerMounter; import noppes.npcs.client.gui.GuiNpcPather; import noppes.npcs.client.gui.GuiNpcRedstoneBlock; @@ -191,6 +192,7 @@ import noppes.npcs.client.renderer.items.ItemShortLampRenderer; import noppes.npcs.client.renderer.items.ItemTallLampRenderer; import noppes.npcs.client.renderer.items.ItemToolRenderer; import noppes.npcs.client.renderer.items.ScriptedBlockItemRenderer; +import noppes.npcs.client.ScriptClientConfig; import noppes.npcs.config.ConfigClient; import noppes.npcs.config.ConfigItem; import noppes.npcs.config.ConfigMain; @@ -333,7 +335,6 @@ public class ClientProxy extends CommonProxy { ClientCloneController.Instance = new ClientCloneController(); ClientTagMapController.Instance = new ClientTagMapController(); - MinecraftForge.EVENT_BUS.register(new ClientEventHandler()); // Telegraph rendering system @@ -472,7 +473,7 @@ public class ClientProxy extends CommonProxy { animNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png"; save = false; } - return new GuiNPCManageAnimations(animNpc, save); + return new GuiNPCManageAnimations(animNpc, save, npc != null); } else if (gui == EnumGuiType.ManageLinked) return new GuiNPCManageLinked(npc); @@ -507,8 +508,10 @@ public class ClientProxy extends CommonProxy { } else { abilityNpc = new EntityCustomNpc(Minecraft.getMinecraft().theWorld); abilityNpc.display.texture = "customnpcs:textures/entity/humanmale/AnimationBody.png"; + abilityNpc.height = 1.8f; + abilityNpc.width = 0.6f; } - return new GuiNpcManageAbilities(abilityNpc); + return new GuiNpcManageAbilities(abilityNpc, npc != null); } else if (gui == EnumGuiType.MainMenuGlobal) @@ -602,7 +605,9 @@ public class ClientProxy extends CommonProxy { return new GuiNpcRedstoneBlock(x, y, z); else if (gui == EnumGuiType.Cloner) - return new GuiNpcMobSpawner(x, y, z); + return GuiNpcMobSpawner.isFullscreen + ? new GuiNpcMobSpawnerFullscreen(x, y, z) + : new GuiNpcMobSpawner(x, y, z); else if (gui == EnumGuiType.MobSpawnerMounter) return new GuiNpcMobSpawnerMounter(x, y, z); @@ -818,6 +823,31 @@ public class ClientProxy extends CommonProxy { } } + @Override + public boolean isScriptingEnabled() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isScriptingEnabled(); + } + + @Override + public boolean isRunLoadedScriptsFirst() { + return ScriptClientConfig.isRunLoadedScriptsFirst(); + } + + @Override + public boolean isGlobalPlayerScripts() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalPlayerScripts(); + } + + @Override + public boolean isGlobalForgeScripts() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalForgeScripts(); + } + + @Override + public boolean isGlobalNPCScripts() { + return ConfigClient.AllowClientScripts && ScriptClientConfig.isGlobalNPCScripts(); + } + public static class FontContainer { public StringCache textFont = null; public boolean useCustomFont = true; diff --git a/src/main/java/noppes/npcs/client/ScriptClientConfig.java b/src/main/java/noppes/npcs/client/ScriptClientConfig.java new file mode 100644 index 000000000..863f991ba --- /dev/null +++ b/src/main/java/noppes/npcs/client/ScriptClientConfig.java @@ -0,0 +1,61 @@ +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 script configuration synced from server. + * Prevents client from using local ConfigScript which may differ from server settings. + * + * IMPORTANT: This class is CLIENT-ONLY. Server-side NBT writing is done in + * ScriptConfigSync to avoid @SideOnly crashes on dedicated servers. + */ +@SideOnly(Side.CLIENT) +public class ScriptClientConfig { + // Cached values from server + private static boolean scriptingEnabled = true; + private static boolean runLoadedScriptsFirst = true; + private static boolean globalPlayerScripts = true; + private static boolean globalForgeScripts = true; + private static boolean globalNPCScripts = false; + + /** + * Update cached config from server NBT data. + * Called when receiving login packet or script sync packets. + */ + public static void readFromNBT(NBTTagCompound compound) { + if (compound == null) return; + + scriptingEnabled = compound.getBoolean("ScriptingEnabled"); + runLoadedScriptsFirst = compound.getBoolean("RunLoadedScriptsFirst"); + globalPlayerScripts = compound.getBoolean("GlobalPlayerScripts"); + globalForgeScripts = compound.getBoolean("GlobalForgeScripts"); + globalNPCScripts = compound.getBoolean("GlobalNPCScripts"); + } + + /** + * Reset to defaults (called on disconnect). + */ + public static void reset() { + scriptingEnabled = true; + runLoadedScriptsFirst = true; + globalPlayerScripts = true; + globalForgeScripts = true; + globalNPCScripts = false; + } + + // Setters for individual packet updates + public static void setScriptingEnabled(boolean value) { scriptingEnabled = value; } + public static void setRunLoadedScriptsFirst(boolean value) { runLoadedScriptsFirst = value; } + public static void setGlobalPlayerScripts(boolean value) { globalPlayerScripts = value; } + public static void setGlobalForgeScripts(boolean value) { globalForgeScripts = value; } + public static void setGlobalNPCScripts(boolean value) { globalNPCScripts = value; } + + // Getters + public static boolean isScriptingEnabled() { return scriptingEnabled; } + public static boolean isRunLoadedScriptsFirst() { return runLoadedScriptsFirst; } + public static boolean isGlobalPlayerScripts() { return globalPlayerScripts; } + public static boolean isGlobalForgeScripts() { return globalForgeScripts; } + public static boolean isGlobalNPCScripts() { return globalNPCScripts; } +} diff --git a/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java b/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java index 81f174170..9e62177f0 100644 --- a/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java +++ b/src/main/java/noppes/npcs/client/controllers/ClientCloneController.java @@ -41,6 +41,26 @@ public class ClientCloneController extends ServerCloneController { return true; } + @Override + public boolean addToTagMap(NBTTagCompound nbttagcompound, String name, String folderName) { + HashSet tagUUIDs = new HashSet<>(); + if (nbttagcompound.hasKey("TagUUIDs")) { + NBTTagList nbtTagList = nbttagcompound.getTagList("TagUUIDs", 8); + for (int i = 0; i < nbtTagList.tagCount(); i++) { + tagUUIDs.add(UUID.fromString(nbtTagList.getStringTagAt(i))); + } + } + + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + if (!tagUUIDs.isEmpty()) { + tagMap.putClone(name, tagUUIDs); + } else { + tagMap.removeClone(name); + } + ClientTagMapController.Instance.saveTagMap(tagMap); + return true; + } + @Override public boolean removeFromTagMap(String name, int tab) { TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab); @@ -51,4 +71,43 @@ public class ClientCloneController extends ServerCloneController { return false; } + @Override + public boolean removeFromTagMap(String name, String folderName) { + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + if (tagMap.removeClone(name)) { + ClientTagMapController.Instance.saveTagMap(tagMap); + return true; + } + return false; + } + + @Override + protected HashSet getTagUUIDsFromTab(String cloneName, int tab) { + TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + @Override + protected HashSet getTagUUIDsFromFolder(String cloneName, String folderName) { + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + @Override + protected void setTagUUIDsForTab(String cloneName, int tab, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ClientTagMapController.Instance.getTagMap(tab); + tagMap.putClone(cloneName, tagUUIDs); + ClientTagMapController.Instance.saveTagMap(tagMap); + } + + @Override + protected void setTagUUIDsForFolder(String cloneName, String folderName, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ClientTagMapController.Instance.getTagMap(folderName); + tagMap.putClone(cloneName, tagUUIDs); + ClientTagMapController.Instance.saveTagMap(tagMap); + } } diff --git a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawner.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawner.java index b3670d9e8..7fd5c174e 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawner.java +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawner.java @@ -2,6 +2,7 @@ package noppes.npcs.client.gui; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; import kamkeel.npcs.network.packets.request.clone.CloneListPacket; import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket; import kamkeel.npcs.network.packets.request.clone.CloneTagListPacket; @@ -26,6 +27,8 @@ 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.GuiNpcTextField; +import noppes.npcs.client.gui.util.IClonerGui; +import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.controllers.data.Tag; import noppes.npcs.controllers.data.TagMap; @@ -38,52 +41,84 @@ import java.util.List; import java.util.Map; import java.util.UUID; -public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { +public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData, ICustomScrollListener, IClonerGui { + + // ==================== STATIC STATE (persists across GUI opens, shared with fullscreen) ==================== + public static boolean isFullscreen = false; + public static int activeTab = 1; + public static String activeFolder = null; + public static int showingClones = 0; // 0=Clones, 1=Entities, 2=Server, 3=Filters + public static String search = ""; + public static String tagSearch = ""; + public static HashMap tags = new HashMap<>(); public static HashMap tagNames = new HashMap<>(); public static HashSet tagFilters = new HashSet<>(); public static byte displayTags = 0; - // 0 - Any, 1 - All, 2 - Not Any, 3 - Not All public static byte filterCondition = 0; - public static byte ascending = 0; - // 0 - By Name, 1 - By Date public static byte sortType = 0; - public TagMap tagMap; + // Scroll position preservation (shared with fullscreen) + public static int savedContentScrollY = 0; + public static int savedNavScrollY = 0; + // ==================== INSTANCE STATE ==================== + public TagMap tagMap; private final GuiCustomScrollCloner scroll = new GuiCustomScrollCloner(this, 0); private final GuiCustomScroll filterScroll = new GuiCustomScroll(this, 1); - private int posX, posY, posZ; - + public int posX, posY, posZ; private List list; private List rawList; private List tagList; - private static int showingClones = 0; - - private static String search = ""; - private static String tagSearch = ""; - - private int activeTab = 1; - + // ==================== CONSTRUCTOR ==================== public GuiNpcMobSpawner(int i, int j, int k) { super(); - xSize = 354; posX = i; posY = j; posZ = k; - - this.closeOnEsc = true; - + closeOnEsc = true; + xSize = 354; setBackground("menubg.png"); PacketClient.sendClient(new CloneAllTagsPacket()); + if (showingClones == 2) { + PacketClient.sendClient(new CloneFolderListPacket()); + } + + // Minimized view doesn't support folders — ensure we're on a tab + if (activeFolder != null) { + if (activeTab < 1 || activeTab > 15) { + activeTab = 1; + } + activeFolder = null; + } } + // ==================== IClonerGui ==================== + @Override + public int getShowingClones() { + return showingClones; + } + + @Override + public HashMap getTags() { + return tags; + } + + @Override + public TagMap getTagMap() { + return tagMap; + } + + // ==================== INIT GUI ==================== public void initGui() { + // Save scroll position before clear + savedContentScrollY = scroll.scrollY; + super.initGui(); guiTop += 10; guiLeft += 30; @@ -92,6 +127,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { scroll.setSize(293, 188); scroll.guiLeft = guiLeft + 4; scroll.guiTop = guiTop + 26; + filterScroll.clear(); filterScroll.setSize(140, 166); filterScroll.guiLeft = guiLeft + 4; @@ -99,112 +135,133 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { filterScroll.multipleSelection = true; filterScroll.setSelectedList(tagFilters); - GuiMenuTopButton button; - addTopButton(button = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones")); - button.active = showingClones == 0; - addTopButton(button = new GuiMenuTopButton(5, button, "gui.server")); - button.active = showingClones == 2; - addTopButton(button = new GuiMenuTopButton(4, button, "spawner.entities")); - button.active = showingClones == 1; - addTopButton(button = new GuiMenuTopButton(16, guiLeft + (xSize - 67), guiTop - 17, "gui.filters")); - button.active = showingClones == 3; - addTopButton(button = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X")); + // Top buttons — build right-to-left to avoid overlap + GuiMenuTopButton closeBtn = new GuiMenuTopButton(17, guiLeft + (xSize - 22), guiTop - 17, "X"); + addTopButton(closeBtn); + + // Position "+" dynamically to the left of "X" + int plusX = closeBtn.xPosition - (fontRendererObj.getStringWidth("+") + 12) - 2; + GuiMenuTopButton fullscreenBtn = new GuiMenuTopButton(61, plusX, guiTop - 17, "+"); + addTopButton(fullscreenBtn); + + // Position "Filters" dynamically to the left of "+" + int filterBtnW = fontRendererObj.getStringWidth(StatCollector.translateToLocal("gui.filters")) + 12; + int filterX = fullscreenBtn.xPosition - filterBtnW - 2; + GuiMenuTopButton filterBtn = new GuiMenuTopButton(16, filterX, guiTop - 17, "gui.filters"); + filterBtn.active = showingClones == 3; + addTopButton(filterBtn); + + // Mode buttons from left + GuiMenuTopButton btn; + addTopButton(btn = new GuiMenuTopButton(3, guiLeft + 4, guiTop - 17, "spawner.clones")); + btn.active = showingClones == 0; + addTopButton(btn = new GuiMenuTopButton(5, btn, "gui.server")); + btn.active = showingClones == 2; + addTopButton(btn = new GuiMenuTopButton(4, btn, "spawner.entities")); + btn.active = showingClones == 1; if (showingClones < 3) { addScroll(scroll); addTextField(new GuiNpcTextField(1, this, fontRendererObj, guiLeft + 4, guiTop + 4, 293, 20, search)); + addButton(new GuiNpcButton(1, guiLeft + 298, guiTop + 6, 52, 20, "item.monsterPlacer.name")); addButton(new GuiNpcButton(2, guiLeft + 298, guiTop + 140, 52, 20, "spawner.mobspawner")); if (showingClones == 0 || showingClones == 2) { - - addSideButton(new GuiMenuSideButton(21, guiLeft - 70, this.guiTop + 2, 70, 22, "1")); - addSideButton(new GuiMenuSideButton(22, guiLeft - 70, this.guiTop + 23, 70, 22, "2")); - addSideButton(new GuiMenuSideButton(23, guiLeft - 70, this.guiTop + 44, 70, 22, "3")); - addSideButton(new GuiMenuSideButton(24, guiLeft - 70, this.guiTop + 65, 70, 22, "4")); - addSideButton(new GuiMenuSideButton(25, guiLeft - 70, this.guiTop + 86, 70, 22, "5")); - addSideButton(new GuiMenuSideButton(26, guiLeft - 70, this.guiTop + 107, 35, 22, "6")); - addSideButton(new GuiMenuSideButton(27, guiLeft - 35, this.guiTop + 107, 35, 22, "7")); - addSideButton(new GuiMenuSideButton(28, guiLeft - 70, this.guiTop + 128, 35, 22, "8")); - addSideButton(new GuiMenuSideButton(29, guiLeft - 35, this.guiTop + 128, 35, 22, "9")); - addSideButton(new GuiMenuSideButton(30, guiLeft - 70, this.guiTop + 149, 35, 22, "10")); - addSideButton(new GuiMenuSideButton(31, guiLeft - 35, this.guiTop + 149, 35, 22, "11")); - addSideButton(new GuiMenuSideButton(32, guiLeft - 70, this.guiTop + 170, 35, 22, "12")); - addSideButton(new GuiMenuSideButton(33, guiLeft - 35, this.guiTop + 170, 35, 22, "13")); - addSideButton(new GuiMenuSideButton(34, guiLeft - 70, this.guiTop + 191, 35, 22, "14")); - addSideButton(new GuiMenuSideButton(35, guiLeft - 35, this.guiTop + 191, 35, 22, "15")); - addButton(new GuiNpcButton(6, guiLeft + 298, guiTop + 190, 52, 20, "gui.remove")); - getSideButton(20 + activeTab).active = true; + initTabSideButtons(); showClones(); + + // Restore scroll position + scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY)); } else { showEntities(); + scroll.scrollY = Math.min(savedContentScrollY, Math.max(0, scroll.maxScrollY)); } } else { - // Show Filters - addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), guiLeft + 7, guiTop + 7)); - addScroll(filterScroll); - addTextField(new GuiNpcTextField(2, this, fontRendererObj, guiLeft + 4, guiTop + 190, 140, 20, tagSearch)); - - addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), guiLeft + 150, guiTop + 27)); - addButton(new GuiNpcButton(12, guiLeft + 215, guiTop + 20, new String[]{"display.show", "display.all", "display.hide"}, displayTags)); - - addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), guiLeft + 150, guiTop + 50)); - addButton(new GuiNpcButton(13, guiLeft + 215, guiTop + 43, new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition)); - - addButton(new GuiNpcButton(11, guiLeft + 150, guiTop + 66, 130, 20, "gui.deselectAll")); - - - addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), guiLeft + 150, guiTop + 112)); - addButton(new GuiNpcButton(14, guiLeft + 215, guiTop + 105, new String[]{"cloner.ascending", "cloner.descending"}, ascending)); - - addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), guiLeft + 150, guiTop + 135)); - addButton(new GuiNpcButton(15, guiLeft + 215, guiTop + 128, new String[]{"cloner.name", "cloner.date"}, sortType)); - - - getButton(12).width = 65; - getButton(12).height = 20; - - getButton(13).width = 65; - getButton(13).height = 20; - - getButton(14).width = 65; - getButton(14).height = 20; - - getButton(15).width = 65; - getButton(15).height = 20; - - showFilters(); + showFiltersPage(); } } - public int getShowingClones() { - return showingClones; + private void initTabSideButtons() { + // Tabs 1-5: full width (70px) + addSideButton(new GuiMenuSideButton(21, guiLeft - 70, guiTop + 2, 70, 22, "1")); + addSideButton(new GuiMenuSideButton(22, guiLeft - 70, guiTop + 23, 70, 22, "2")); + addSideButton(new GuiMenuSideButton(23, guiLeft - 70, guiTop + 44, 70, 22, "3")); + addSideButton(new GuiMenuSideButton(24, guiLeft - 70, guiTop + 65, 70, 22, "4")); + addSideButton(new GuiMenuSideButton(25, guiLeft - 70, guiTop + 86, 70, 22, "5")); + // Tabs 6-15: half width (35px), 2-column grid + addSideButton(new GuiMenuSideButton(26, guiLeft - 70, guiTop + 107, 35, 22, "6")); + addSideButton(new GuiMenuSideButton(27, guiLeft - 35, guiTop + 107, 35, 22, "7")); + addSideButton(new GuiMenuSideButton(28, guiLeft - 70, guiTop + 128, 35, 22, "8")); + addSideButton(new GuiMenuSideButton(29, guiLeft - 35, guiTop + 128, 35, 22, "9")); + addSideButton(new GuiMenuSideButton(30, guiLeft - 70, guiTop + 149, 35, 22, "10")); + addSideButton(new GuiMenuSideButton(31, guiLeft - 35, guiTop + 149, 35, 22, "11")); + addSideButton(new GuiMenuSideButton(32, guiLeft - 70, guiTop + 170, 35, 22, "12")); + addSideButton(new GuiMenuSideButton(33, guiLeft - 35, guiTop + 170, 35, 22, "13")); + addSideButton(new GuiMenuSideButton(34, guiLeft - 70, guiTop + 191, 35, 22, "14")); + addSideButton(new GuiMenuSideButton(35, guiLeft - 35, guiTop + 191, 35, 22, "15")); + + if (activeTab >= 1 && activeTab <= 15) { + GuiMenuSideButton active = getSideButton(20 + activeTab); + if (active != null) active.active = true; + } } - public void showFilters() { + // ==================== FILTERS PAGE ==================== + private void showFiltersPage() { + int baseY = guiTop; + + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), + guiLeft + 7, baseY + 7)); + + filterScroll.clear(); + filterScroll.setSize(140, 166); + filterScroll.guiLeft = guiLeft + 4; + filterScroll.guiTop = baseY + 19; + filterScroll.multipleSelection = true; + filterScroll.setSelectedList(tagFilters); + addScroll(filterScroll); + + addTextField(new GuiNpcTextField(2, this, fontRendererObj, + guiLeft + 4, baseY + 190, 140, 20, tagSearch)); + + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), + guiLeft + 150, baseY + 27)); + addButton(new GuiNpcButton(12, guiLeft + 215, baseY + 20, + new String[]{"display.show", "display.all", "display.hide"}, displayTags)); + + addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), + guiLeft + 150, baseY + 50)); + addButton(new GuiNpcButton(13, guiLeft + 215, baseY + 43, + new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, filterCondition)); + + addButton(new GuiNpcButton(11, guiLeft + 150, baseY + 66, 130, 20, "gui.deselectAll")); + + addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), + guiLeft + 150, baseY + 112)); + addButton(new GuiNpcButton(14, guiLeft + 215, baseY + 105, + new String[]{"cloner.ascending", "cloner.descending"}, ascending)); + + addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), + guiLeft + 150, baseY + 135)); + addButton(new GuiNpcButton(15, guiLeft + 215, baseY + 128, + new String[]{"cloner.name", "cloner.date"}, sortType)); + + getButton(12).width = 65; + getButton(12).height = 20; + getButton(13).width = 65; + getButton(13).height = 20; + getButton(14).width = 65; + getButton(14).height = 20; + getButton(15).width = 65; + getButton(15).height = 20; + filterScroll.setList(getTagList()); } - private void showEntities() { - Map data = EntityList.stringToClassMapping; - ArrayList list = new ArrayList(); - for (Object name : data.keySet()) { - Class c = (Class) data.get(name); - try { - if (EntityLiving.class.isAssignableFrom(c) && c.getConstructor(new Class[]{World.class}) != null && !Modifier.isAbstract(c.getModifiers())) - list.add(name.toString()); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - } - } - this.list = list; - this.rawList = new ArrayList(this.list); - scroll.setList(getSearchList(), ascending == 0, sortType == 0); - } - + // ==================== CLONE / ENTITY DISPLAY ==================== private void showClones() { if (showingClones == 2) { PacketClient.sendClient(new CloneTagListPacket(activeTab)); @@ -219,16 +276,41 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } this.tagMap = ClientTagMapController.Instance.getTagMap(activeTab); + populateRawListWithTags(); + scroll.setList(getSearchList(), ascending == 0, sortType == 0); + } + + private void showEntities() { + Map data = EntityList.stringToClassMapping; + ArrayList list = new ArrayList(); + for (Object name : data.keySet()) { + Class c = (Class) data.get(name); + try { + if (EntityLiving.class.isAssignableFrom(c) + && c.getConstructor(new Class[]{World.class}) != null + && !Modifier.isAbstract(c.getModifiers())) + list.add(name.toString()); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + } + } + this.list = list; this.rawList = new ArrayList(this.list); + scroll.setList(getSearchList(), ascending == 0, sortType == 0); + } + + private void populateRawListWithTags() { + this.rawList = new ArrayList<>(this.list); if (this.tagMap != null) { - if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { + if (displayTags == 0 || displayTags == 1) { for (int i = 0; i < this.list.size(); i++) { StringBuilder npcName = new StringBuilder(list.get(i)); if (this.tagMap.hasClone(list.get(i))) { for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) { Tag tag = tags.get(tagUUID); if (tag != null) { - if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { + if (displayTags == 1 || !tag.getIsHidden()) { npcName.append(" [" + tag.name + "]"); } } @@ -238,27 +320,26 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } } - - scroll.setList(getSearchList(), ascending == 0, sortType == 0); } - public void keyTyped(char c, int i) { - super.keyTyped(c, i); - if (getTextField(1) != null) { - if (search.equals(getTextField(1).getText())) - return; - search = getTextField(1).getText().toLowerCase(); - scroll.setList(getSearchList(), ascending == 0, sortType == 0); - } - if (getTextField(2) != null) { - if (tagSearch.equals(getTextField(2).getText())) - return; - tagSearch = getTextField(2).getText().toLowerCase(); - filterScroll.setList(getTagList()); - } + private NBTTagCompound getCompound() { + String sel = scroll.getSelected(); + if (sel == null) + return null; + if (showingClones == 0) { + return ClientCloneController.Instance.getCloneData(player, sel, activeTab); + } else { + Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld); + if (entity == null) + return null; + NBTTagCompound compound = new NBTTagCompound(); + entity.writeToNBTOptional(compound); + return compound; + } } + // ==================== SEARCH / FILTER ==================== private List getSearchList() { if (this.list == null) { this.list = new ArrayList(); @@ -269,10 +350,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { // No Filters - or - Entities if (tagFilters.size() == 0 || showingClones == 1) { - // No Search if (search.isEmpty()) return new ArrayList(this.list); - // Yes Search else { List list = new ArrayList(); for (int i = 0; i < this.list.size(); i++) { @@ -284,10 +363,7 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } - //////////////////////// - //// WITH FILTERS - - // No Search + // With Filters if (search.isEmpty()) { List list = new ArrayList(); for (String name : this.list) { @@ -300,7 +376,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { return list; } - // Yes Search List list = new ArrayList(); for (int i = 0; i < this.list.size(); i++) { if (this.rawList.get(i).toLowerCase().contains(search)) { @@ -311,7 +386,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } } - } return list; } @@ -346,7 +420,6 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } } } - return conditionMet; } @@ -354,10 +427,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { if (this.tagList == null) { this.tagList = new ArrayList(); } - // No Search // No Filters - or - Entities if (tagSearch.isEmpty()) return new ArrayList(tagNames.keySet()); - // Yes Search // No Filters - or - Entities List list = new ArrayList(); for (String name : this.tagList) { @@ -367,125 +438,162 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { return list; } - private NBTTagCompound getCompound() { - String sel = scroll.getSelected(); - if (sel == null) - return null; - - if (showingClones == 0) { - return ClientCloneController.Instance.getCloneData(player, sel, activeTab); - } else { - Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld); - if (entity == null) - return null; - NBTTagCompound compound = new NBTTagCompound(); - entity.writeToNBTOptional(compound); - return compound; - } + // ==================== MOUSE / KEYBOARD EVENTS ==================== + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { } + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + } + + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + + GuiNpcTextField searchField = getTextField(1); + if (searchField != null) { + String newText = searchField.getText().toLowerCase(); + if (!search.equals(newText)) { + search = newText; + scroll.setList(getSearchList(), ascending == 0, sortType == 0); + } + } + + GuiNpcTextField tagSearchField = getTextField(2); + if (tagSearchField != null) { + String newText = tagSearchField.getText().toLowerCase(); + if (!tagSearch.equals(newText)) { + tagSearch = newText; + filterScroll.setList(getTagList()); + } + } + } + + // ==================== BUTTON ACTIONS ==================== @Override protected void actionPerformed(GuiButton guibutton) { int id = guibutton.id; - if (id == 0) { - close(); - } - if (id == 1) { - if (showingClones == 2) { - String sel = scroll.getSelected(); - if (sel == null) - return; - SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab); - close(); - } else { - NBTTagCompound compound = getCompound(); - if (compound == null) - return; - SpawnMobPacket.Client(posX, posY, posZ, compound); - close(); - } - } - if (id == 2) { - if (showingClones == 2) { - String sel = scroll.getSelected(); - if (sel == null) - return; - MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab); - close(); - } else { - NBTTagCompound compound = getCompound(); - if (compound == null) - return; - MobSpawnerPacket.Client(posX, posY, posZ, compound); - close(); - } + // Tab side buttons (IDs 21-35) + if (id >= 21 && id <= 35) { + activeTab = id - 20; + activeFolder = null; + initGui(); + return; } + + // Mode buttons if (id == 3) { + savedContentScrollY = 0; showingClones = 0; initGui(); } if (id == 4) { + savedContentScrollY = 0; showingClones = 1; initGui(); } if (id == 5) { + savedContentScrollY = 0; showingClones = 2; + PacketClient.sendClient(new CloneFolderListPacket()); initGui(); } if (id == 16) { + savedContentScrollY = 0; showingClones = 3; initGui(); } if (id == 17) { close(); } + + // Open fullscreen GUI + if (id == 61) { + isFullscreen = true; + Minecraft.getMinecraft().displayGuiScreen( + new GuiNpcMobSpawnerFullscreen(posX, posY, posZ)); + } + + // Spawn + if (id == 1) { + if (showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + SpawnMobPacket.Server(posX, posY, posZ, sel, activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + SpawnMobPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Mob Spawner + if (id == 2) { + if (showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + MobSpawnerPacket.Server(posX, posY, posZ, sel, activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + MobSpawnerPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Remove if (id == 6) { if (scroll.getSelected() != null) { + int prevSelected = scroll.selected; if (showingClones == 2) { PacketClient.sendClient(new CloneRemovePacket(activeTab, scroll.getSelected())); return; } ClientCloneController.Instance.removeClone(scroll.getSelected(), activeTab); - scroll.selected = -1; initGui(); + if (scroll.list != null && !scroll.list.isEmpty()) { + scroll.selected = Math.min(prevSelected, scroll.list.size() - 1); + } else { + scroll.selected = -1; + } } } + + // Filter controls if (id == 11) { tagFilters = new HashSet<>(); filterScroll.setSelectedList(tagFilters); initGui(); } if (id == 12) { - GuiNpcButton button = (GuiNpcButton) guibutton; - displayTags = (byte) button.getValue(); + displayTags = (byte) ((GuiNpcButton) guibutton).getValue(); } if (id == 13) { - GuiNpcButton button = (GuiNpcButton) guibutton; - filterCondition = (byte) button.getValue(); + filterCondition = (byte) ((GuiNpcButton) guibutton).getValue(); } if (id == 14) { - GuiNpcButton button = (GuiNpcButton) guibutton; - ascending = (byte) button.getValue(); + ascending = (byte) ((GuiNpcButton) guibutton).getValue(); } if (id == 15) { - GuiNpcButton button = (GuiNpcButton) guibutton; - sortType = (byte) button.getValue(); - } - if (id > 20) { - activeTab = id - 20; - initGui(); + sortType = (byte) ((GuiNpcButton) guibutton).getValue(); } } + // ==================== DATA FROM SERVER ==================== @Override public void save() { - } @Override public void setGuiData(NBTTagCompound compound) { - if (compound.hasKey("CloneTags")) { + if (compound.hasKey("CloneFolders")) { + // Minimized doesn't use folders, but still handle the packet + initGui(); + } else if (compound.hasKey("CloneTags")) { this.tagMap = new TagMap(activeTab); NBTTagCompound cloneTags = compound.getCompoundTag("CloneTags"); this.tagMap.readNBT(cloneTags); @@ -521,29 +629,8 @@ public class GuiNpcMobSpawner extends GuiNPCInterface implements IGuiData { } this.list = list; - - this.rawList = new ArrayList(this.list); - if (this.tagMap != null) { - if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { - for (int i = 0; i < this.list.size(); i++) { - StringBuilder npcName = new StringBuilder(list.get(i)); - if (this.tagMap.hasClone(list.get(i))) { - for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) { - Tag tag = tags.get(tagUUID); - if (tag != null) { - if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { - npcName.append(" [" + tag.name + "]"); - } - } - } - } - this.rawList.set(i, npcName.toString()); - } - } - } - + populateRawListWithTags(); scroll.setList(getSearchList(), ascending == 0, sortType == 0); } } - } diff --git a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java index d2895fc44..5cea7fe28 100644 --- a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerAdd.java @@ -2,6 +2,7 @@ package noppes.npcs.client.gui; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.clone.CloneAllTagsShortPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; import kamkeel.npcs.network.packets.request.clone.ClonePreSavePacket; import kamkeel.npcs.network.packets.request.clone.CloneSavePacket; import net.minecraft.client.Minecraft; @@ -22,12 +23,14 @@ import noppes.npcs.client.gui.util.GuiNpcTextField; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.client.gui.util.ISubGuiListener; import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.CloneFolder; import noppes.npcs.controllers.data.Tag; import noppes.npcs.entity.EntityNPCInterface; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.UUID; public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCallback, IGuiData, ISubGuiListener { @@ -35,9 +38,16 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall private Entity toClone; private NBTTagCompound compound; private static boolean serverSide = false; + private static int saveMode = 0; // 0=Tab, 1=Folder private static int tab = 1; + private static String folder = null; public boolean isNPC = false; + // Client-side folder names + private ArrayList clientFolderNames = new ArrayList<>(); + // Server-side folder names (populated via CloneFolderListPacket) + private static ArrayList serverFolderNames = new ArrayList<>(); + // Selected Tags to Add public static NBTTagList tagsCompound; public static HashSet addTags; @@ -68,6 +78,37 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall if (isNPC) { PacketClient.sendClient(new CloneAllTagsShortPacket()); } + + buildClientFolderNames(); + + // Request server folders if in server mode + if (serverSide) { + PacketClient.sendClient(new CloneFolderListPacket()); + } + + // Validate saved folder selection + validateFolder(); + } + + private void buildClientFolderNames() { + clientFolderNames.clear(); + if (ClientCloneController.Instance != null) { + for (CloneFolder f : ClientCloneController.Instance.getFolderList()) { + clientFolderNames.add(f.name); + } + } + } + + private List getActiveFolderList() { + return serverSide ? serverFolderNames : clientFolderNames; + } + + private void validateFolder() { + if (saveMode == 1 && folder != null) { + if (!getActiveFolderList().contains(folder)) { + folder = null; + } + } } @Override @@ -77,61 +118,138 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall addLabel(new GuiNpcLabel(0, "Save as", guiLeft + 4, guiTop + 6)); addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 4, guiTop + 18, 200, 20, name)); + // Tab/Folder toggle + addButton(new GuiNpcButton(6, guiLeft + 4, guiTop + 45, 50, 20, + new String[]{"Tab", "Folder"}, saveMode)); - addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50)); - addButton(new GuiButtonBiDirectional(2, guiLeft + 40, guiTop + 45, 60, 20, new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}, tab - 1)); + // Destination selector based on saveMode + if (saveMode == 0) { + // Tab selector: 1-15 + String[] tabLabels = new String[15]; + for (int i = 0; i < 15; i++) tabLabels[i] = String.valueOf(i + 1); + int selectedTab = (tab >= 1 && tab <= 15) ? tab - 1 : 0; + addButton(new GuiButtonBiDirectional(2, guiLeft + 56, guiTop + 45, 90, 20, tabLabels, selectedTab)); + } else { + // Folder selector button — opens SubGuiFolderSelect + String btnText = folder != null ? folder : "Select a Folder"; + addButton(new GuiNpcButton(2, guiLeft + 56, guiTop + 45, 148, 20, btnText)); + } - addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0)); - addLabel(new GuiNpcLabel(1, "Tab", guiLeft + 10, guiTop + 50)); - - addButton(new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save")); + // Save / Cancel + GuiNpcButton saveBtn = new GuiNpcButton(0, guiLeft + 4, guiTop + 70, 80, 20, "gui.save"); + if (saveMode == 1 && folder == null) { + saveBtn.enabled = false; + } + addButton(saveBtn); addButton(new GuiNpcButton(1, guiLeft + 86, guiTop + 70, 80, 20, "gui.cancel")); + // Client / Server toggle + addButton(new GuiNpcButton(3, guiLeft + 4, guiTop + 95, new String[]{"Client side", "Server side"}, serverSide ? 1 : 0)); + if (isNPC) { addButton(new GuiNpcButton(4, guiLeft + 4, guiTop + 120, 99, 20, "cloner.wandTags")); addButton(new GuiNpcButton(5, guiLeft + 106, guiTop + 120, 99, 20, "cloner.npcTags")); if (addTags.size() > 0) { - addLabel(new GuiNpcLabel(6, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160)); + addLabel(new GuiNpcLabel(8, "cloner.wandtagsapplied", guiLeft + 10, guiTop + 160)); } } } + private void updateDestinationFromSelector() { + if (saveMode == 0) { + GuiNpcButton selector = getButton(2); + if (selector == null) return; + tab = selector.getValue() + 1; + folder = null; + } + // In folder mode, folder is already set via SubGuiFolderSelect + } + public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; + + // Save if (id == 0) { + updateDestinationFromSelector(); String name = getTextField(0).getText(); if (name.isEmpty()) return; - int tab = ((GuiNpcButton) guibutton).getValue() + 1; + + if (saveMode == 1 && folder == null) + return; + if (!serverSide) { - if (ClientCloneController.Instance.getCloneData(null, name, tab) != null) + boolean exists; + if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) { + exists = ClientCloneController.Instance.getCloneData(null, name, folder) != null; + } else { + exists = ClientCloneController.Instance.getCloneData(null, name, tab) != null; + } + if (exists) displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1)); else confirmClicked(true, 0); - } else - PacketClient.sendClient(new ClonePreSavePacket(name, tab)); + } else { + if (saveMode == 1 && folder != null) { + PacketClient.sendClient(new ClonePreSavePacket(name, folder)); + } else { + PacketClient.sendClient(new ClonePreSavePacket(name, tab)); + } + } } + + // Cancel if (id == 1) { close(); } + + // Destination selector if (id == 2) { - tab = ((GuiNpcButton) guibutton).getValue() + 1; + if (saveMode == 0) { + // Tab mode — update from BiDirectional + updateDestinationFromSelector(); + } else { + // Folder mode — open folder selector Sub GUI + List folders = getActiveFolderList(); + setSubGui(new SubGuiFolderSelect(folders, folder)); + } } + + // Client / Server toggle if (id == 3) { + boolean wasServerSide = serverSide; serverSide = ((GuiNpcButton) guibutton).getValue() == 1; + + if (serverSide && !wasServerSide) { + // Switching to server mode — request fresh folder list + PacketClient.sendClient(new CloneFolderListPacket()); + } + + // Validate folder exists on the new side + validateFolder(); + initGui(); } + + // Wand Tags if (id == 4) { if (isNPC) { this.setSubGui(new SubGuiClonerQuickTags(this)); } } + + // NPC Tags if (id == 5) { if (isNPC) { this.setSubGui(new SubGuiClonerNPCTags((EntityNPCInterface) toClone, this)); } } - } + // Tab/Folder mode toggle + if (id == 6) { + saveMode = ((GuiNpcButton) guibutton).getValue(); + initGui(); + } + } @Override public void confirmClicked(boolean confirm, int id) { @@ -145,13 +263,21 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall if (isNPC) { compound.setTag("TagUUIDs", tagsCompound); } - ClientCloneController.Instance.addClone(compound, name, tab, extraTags); + if (saveMode == 1 && folder != null && ClientCloneController.Instance != null) { + ClientCloneController.Instance.addClone(compound, name, folder, extraTags); + } else { + ClientCloneController.Instance.addClone(compound, name, tab, extraTags); + } } else { NBTTagCompound compounder = new NBTTagCompound(); if (isNPC) { compounder.setTag("TagUUIDs", tagsCompound); } - PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder)); + if (saveMode == 1 && folder != null) { + PacketClient.sendClient(new CloneSavePacket(name, folder, extraTags, compounder)); + } else { + PacketClient.sendClient(new CloneSavePacket(name, tab, extraTags, compounder)); + } } close(); @@ -159,7 +285,6 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall displayGuiScreen(this); } - @Override public void save() { } @@ -171,6 +296,17 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall displayGuiScreen(new GuiYesNo(this, "Warning", "You are about to overwrite a clone", 1)); else confirmClicked(true, 0); + } else if (compound.hasKey("CloneFolders")) { + // Server folder list arrived + NBTTagList folderList = compound.getTagList("CloneFolders", 10); + serverFolderNames.clear(); + for (int i = 0; i < folderList.tagCount(); i++) { + CloneFolder f = new CloneFolder(); + f.readNBT(folderList.getCompoundTagAt(i)); + serverFolderNames.add(f.name); + } + validateFolder(); + initGui(); } else if (compound.hasKey("ShortTags")) { NBTTagList validTags = compound.getTagList("ShortTags", 10); tagMap.clear(); @@ -193,6 +329,12 @@ public class GuiNpcMobSpawnerAdd extends GuiNPCInterface implements GuiYesNoCall @Override public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiFolderSelect) { + SubGuiFolderSelect sel = (SubGuiFolderSelect) subgui; + if (sel.selectedFolder != null) { + folder = sel.selectedFolder; + } + } initGui(); } diff --git a/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java new file mode 100644 index 000000000..4919ccbae --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerFullscreen.java @@ -0,0 +1,1045 @@ +package noppes.npcs.client.gui; + +import kamkeel.npcs.network.PacketClient; +import kamkeel.npcs.network.packets.request.clone.CloneAllTagsPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderCrudPacket; +import kamkeel.npcs.network.packets.request.clone.CloneFolderListPacket; +import kamkeel.npcs.network.packets.request.clone.CloneListPacket; +import kamkeel.npcs.network.packets.request.clone.CloneMovePacket; +import kamkeel.npcs.network.packets.request.clone.CloneRemovePacket; +import kamkeel.npcs.network.packets.request.clone.CloneTagListPacket; +import kamkeel.npcs.network.packets.request.clone.MobSpawnerPacket; +import kamkeel.npcs.network.packets.request.clone.SpawnMobPacket; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityList; +import net.minecraft.entity.EntityLiving; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.StatCollector; +import net.minecraft.world.World; +import noppes.npcs.client.controllers.ClientCloneController; +import noppes.npcs.client.controllers.ClientTagMapController; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiCustomScrollCloner; +import noppes.npcs.client.gui.util.GuiCustomScrollIcons; +import noppes.npcs.client.gui.util.GuiDirectory; +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.IClonerGui; +import noppes.npcs.client.gui.util.IGuiData; +import noppes.npcs.client.gui.util.SubGuiInterface; +import noppes.npcs.controllers.data.CloneFolder; +import noppes.npcs.controllers.data.Tag; +import noppes.npcs.controllers.data.TagMap; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class GuiNpcMobSpawnerFullscreen extends GuiDirectory implements IGuiData, IClonerGui { + + // ==================== INSTANCE STATE ==================== + public TagMap tagMap; + private final GuiCustomScrollCloner scroll = new GuiCustomScrollCloner(this, 0); + private final GuiCustomScroll filterScroll = new GuiCustomScroll(this, 1); + private final GuiCustomScrollIcons navScroll = new GuiCustomScrollIcons(this, 2); + + private int posX, posY, posZ; + private List list; + private List rawList; + private List tagList; + private List folderNames = new ArrayList<>(); + + // Left nav list data + private List navNames = new ArrayList<>(); + private List navIcons = new ArrayList<>(); + private String navSearch = ""; + + // Move workflow state + private int movePhase = 0; // 0=off, 1=selecting clones, 2=selecting destination + private HashSet moveSelection = new HashSet<>(); + + // ==================== CONSTRUCTOR ==================== + public GuiNpcMobSpawnerFullscreen(int posX, int posY, int posZ) { + super(); + this.posX = posX; + this.posY = posY; + this.posZ = posZ; + + // Configure GuiDirectory layout percentages + leftPanelPercent = 0.15f; + rightPanelPercent = 0.08f; + minLeftPanelW = 120; + minRightPanelW = 62; + + PacketClient.sendClient(new CloneAllTagsPacket()); + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderListPacket()); + } + loadFolderNames(); + } + + private void loadFolderNames() { + folderNames.clear(); + if (ClientCloneController.Instance != null) { + for (CloneFolder folder : ClientCloneController.Instance.getFolderList()) { + folderNames.add(folder.name); + } + } + } + + // ==================== IClonerGui ==================== + @Override + public int getShowingClones() { + return GuiNpcMobSpawner.showingClones; + } + + @Override + public HashMap getTags() { + return GuiNpcMobSpawner.tags; + } + + @Override + public TagMap getTagMap() { + return tagMap; + } + + // ==================== GuiDirectory HOOKS ==================== + @Override + public void initGui() { + // Save scroll positions before super.initGui() clears everything + GuiNpcMobSpawner.savedContentScrollY = scroll.scrollY; + GuiNpcMobSpawner.savedNavScrollY = navScroll.scrollY; + + super.initGui(); + } + + @Override + protected void drawPanels() { + if (GuiNpcMobSpawner.showingClones < 3) { + super.drawPanels(); + } else { + // Filters page: only draw top bar, no side panels + } + } + + @Override + protected void initTopBar(int topBtnY) { + int topBtnW = 55; + int x = originX + 2; + + GuiNpcButton clonesBtn = new GuiNpcButton(3, x, topBtnY, topBtnW, btnH, "spawner.clones"); + clonesBtn.enabled = GuiNpcMobSpawner.showingClones != 0; + addButton(clonesBtn); + x += topBtnW + 2; + + GuiNpcButton serverBtn = new GuiNpcButton(5, x, topBtnY, topBtnW, btnH, "gui.server"); + serverBtn.enabled = GuiNpcMobSpawner.showingClones != 2; + addButton(serverBtn); + x += topBtnW + 2; + + GuiNpcButton entitiesBtn = new GuiNpcButton(4, x, topBtnY, topBtnW, btnH, "spawner.entities"); + entitiesBtn.enabled = GuiNpcMobSpawner.showingClones != 1; + addButton(entitiesBtn); + + // Top bar right side + int closeX = originX + usableW - btnH - 2; + addButton(new GuiNpcButton(17, closeX, topBtnY, btnH, btnH, "X")); + int minimizeX = closeX - btnH - 2; + addButton(new GuiNpcButton(61, minimizeX, topBtnY, btnH, btnH, "-")); + int filterBtnW = 50; + int filterX = minimizeX - filterBtnW - 2; + GuiNpcButton filterBtn = new GuiNpcButton(16, filterX, topBtnY, filterBtnW, btnH, "gui.filters"); + filterBtn.enabled = GuiNpcMobSpawner.showingClones != 3; + addButton(filterBtn); + + // Clone search field in top bar (only when not on filters page) + if (GuiNpcMobSpawner.showingClones < 3) { + int searchX = x + topBtnW + 6; + int searchW = filterX - searchX - 4; + if (searchW > 20) { + addTextField(new GuiNpcTextField(1, this, fontRendererObj, + searchX, topBtnY, searchW, btnH, GuiNpcMobSpawner.search)); + } + } + + // Disable mode buttons during move + if (movePhase > 0) { + clonesBtn.enabled = false; + serverBtn.enabled = false; + entitiesBtn.enabled = false; + filterBtn.enabled = false; + } + } + + @Override + protected void initLeftPanel() { + if (GuiNpcMobSpawner.showingClones >= 3) return; + + boolean folderSelected = GuiNpcMobSpawner.activeFolder != null; + int bottomRows = folderSelected ? 3 : 2; + int bottomH = bottomRows * (btnH + gap); + int navH = contentH - bottomH; + buildNavList(); + + int savedNavScroll = GuiNpcMobSpawner.savedNavScrollY; + navScroll.clear(); + navScroll.colors.clear(); + navScroll.setSize(leftPanelW, navH); + navScroll.guiLeft = originX; + navScroll.guiTop = contentY; + navScroll.setListWithIcons(navNames, navIcons); + navScroll.setSelected(getNavSelection()); + navScroll.scrollY = Math.min(savedNavScroll, Math.max(0, navScroll.maxScrollY)); + + // Phase 2: color nav items orange (selectable) or red (current location, not selectable) + if (movePhase == 2) { + String currentNav = getNavSelection(); + for (String name : navNames) { + navScroll.colors.put(name, name.equals(currentNav) ? 0xFF5555 : 0xFFAA00); + } + } + + addScroll(navScroll); + + // Nav search field below the scroll + int navSearchY = contentY + navH + gap; + addTextField(new GuiNpcTextField(3, this, fontRendererObj, + originX, navSearchY, leftPanelW, btnH, navSearch)); + + // Add folder button + int addFolderY = navSearchY + btnH + gap; + GuiNpcButton addFolderBtn = new GuiNpcButton(40, originX, addFolderY, leftPanelW, btnH, "+ Add Folder"); + if (movePhase > 0) addFolderBtn.enabled = false; + addButton(addFolderBtn); + + // Rename/Delete folder buttons (only when a folder is selected) + if (folderSelected) { + int folderCrudY = addFolderY + btnH + gap; + int halfW = (leftPanelW - gap) / 2; + GuiNpcButton renameBtn = new GuiNpcButton(41, originX, folderCrudY, halfW, btnH, "Rename"); + if (movePhase > 0) renameBtn.enabled = false; + addButton(renameBtn); + GuiNpcButton delBtn = new GuiNpcButton(42, originX + halfW + gap, folderCrudY, halfW, btnH, "gui.remove"); + if (ClientCloneController.Instance != null) { + List clones = ClientCloneController.Instance.getClones(GuiNpcMobSpawner.activeFolder); + delBtn.enabled = clones == null || clones.isEmpty(); + } + if (movePhase > 0) delBtn.enabled = false; + addButton(delBtn); + } + } + + @Override + protected void initCenterPanel() { + if (GuiNpcMobSpawner.showingClones >= 3) { + showFiltersPage(); + return; + } + + int savedScroll = GuiNpcMobSpawner.savedContentScrollY; + scroll.clear(); + scroll.setSize(contentW, contentH); + scroll.guiLeft = contentX; + scroll.guiTop = contentY; + addScroll(scroll); + + if (GuiNpcMobSpawner.showingClones == 0 || GuiNpcMobSpawner.showingClones == 2) { + // Always clear colors — only phase 2 re-populates them + scroll.colors.clear(); + + // Multi-select mode during move phase 1 + if (movePhase == 1) { + scroll.multipleSelection = true; + scroll.setSelectable(true); + scroll.setSelectedList(moveSelection); + } else if (movePhase == 2) { + // Phase 2: show selection as yellow, freeze scroll + scroll.multipleSelection = true; + scroll.setSelectedList(moveSelection); + scroll.setSelectable(false); + } else { + scroll.multipleSelection = false; + scroll.setSelectable(true); + } + + showClones(); + + // Phase 2: color selected clones yellow + if (movePhase == 2) { + for (String name : moveSelection) { + scroll.colors.put(name, 0xFFFF55); + } + } + + // Restore scroll position after list is populated + scroll.scrollY = Math.min(savedScroll, Math.max(0, scroll.maxScrollY)); + } else { + showEntities(); + scroll.scrollY = Math.min(savedScroll, Math.max(0, scroll.maxScrollY)); + } + } + + @Override + protected void initRightPanel(int startY) { + if (GuiNpcMobSpawner.showingClones >= 3) return; + + int btnGap = 4; + int panelH = contentH - 4; + int midY = startY + (panelH / 2); + int bottomY = contentY + contentH - btnH; + + // Spawn — top + GuiNpcButton spawnBtn = new GuiNpcButton(1, rightX, startY, rightPanelW, btnH, "item.monsterPlacer.name"); + if (movePhase > 0) spawnBtn.enabled = false; + addButton(spawnBtn); + + // Spawner — below midpoint + GuiNpcButton spawnerBtn = new GuiNpcButton(2, rightX, midY + btnGap / 2, rightPanelW, btnH, "spawner.mobspawner"); + if (movePhase > 0) spawnerBtn.enabled = false; + addButton(spawnerBtn); + + if (GuiNpcMobSpawner.showingClones == 0 || GuiNpcMobSpawner.showingClones == 2) { + // Move — above midpoint + String moveLabel = movePhase > 0 ? "Moving" : "Move"; + GuiNpcButton moveBtn = new GuiNpcButton(50, rightX, midY - btnH - btnGap / 2, rightPanelW, btnH, moveLabel); + addButton(moveBtn); + + // Confirm — below Move (only visible during phase 1) + if (movePhase == 1) { + GuiNpcButton confirmBtn = new GuiNpcButton(51, rightX, midY - btnH - btnGap / 2 + btnH + btnGap, rightPanelW, btnH, "Confirm"); + confirmBtn.enabled = !moveSelection.isEmpty(); + addButton(confirmBtn); + } + + // Remove — bottom + GuiNpcButton removeBtn = new GuiNpcButton(6, rightX, bottomY, rightPanelW, btnH, "gui.remove"); + if (movePhase > 0) removeBtn.enabled = false; + addButton(removeBtn); + } + } + + // ==================== OVERLAY DRAWING ==================== + @Override + protected void drawOverlay(int mouseX, int mouseY, float partialTicks) { + if (movePhase == 1) { + String text = "Select Clones to Move"; + int textW = fontRendererObj.getStringWidth(text); + fontRendererObj.drawStringWithShadow(text, width / 2 - textW / 2, height - pad - 10, 0x55FF55); + } else if (movePhase == 2) { + String text = "Select a Tab or Folder"; + int textW = fontRendererObj.getStringWidth(text); + fontRendererObj.drawStringWithShadow(text, width / 2 - textW / 2, height - pad - 10, 0xFF5555); + } + } + + // ==================== LEFT NAVIGATION ==================== + private void buildNavList() { + navNames.clear(); + navIcons.clear(); + + String searchLower = navSearch.toLowerCase(); + + for (int i = 1; i <= 15; i++) { + String name = "Tab " + i; + if (searchLower.isEmpty() || name.toLowerCase().contains(searchLower)) { + navNames.add(name); + navIcons.add(GuiCustomScrollIcons.ICON_TAB); + } + } + for (String folder : folderNames) { + if (searchLower.isEmpty() || folder.toLowerCase().contains(searchLower)) { + navNames.add(folder); + navIcons.add(GuiCustomScrollIcons.ICON_FOLDER); + } + } + } + + private String getNavSelection() { + if (GuiNpcMobSpawner.activeFolder != null) return GuiNpcMobSpawner.activeFolder; + if (GuiNpcMobSpawner.activeTab >= 1 && GuiNpcMobSpawner.activeTab <= 15) { + return "Tab " + GuiNpcMobSpawner.activeTab; + } + return "Tab 1"; + } + + private void handleNavClick(String selected) { + if (selected == null) return; + + if (selected.startsWith("Tab ")) { + try { + int tabNum = Integer.parseInt(selected.substring(4)); + if (tabNum >= 1 && tabNum <= 15) { + GuiNpcMobSpawner.activeTab = tabNum; + GuiNpcMobSpawner.activeFolder = null; + initGui(); + return; + } + } catch (NumberFormatException ignored) { + } + } + + GuiNpcMobSpawner.activeFolder = selected; + GuiNpcMobSpawner.activeTab = -1; + initGui(); + } + + // ==================== FILTERS PAGE ==================== + private void showFiltersPage() { + int scrollW = Math.min(usableW / 2 - gap * 2, 240); + int scrollX = originX + gap; + int scrollTopY = contentY + 16; + int scrollH = contentH - 16 - btnH - gap * 2; + + addLabel(new GuiNpcLabel(1, StatCollector.translateToLocal("cloner.tagFilters"), + scrollX + 2, contentY + 4, 0xFFFFFF)); + + filterScroll.clear(); + filterScroll.setSize(scrollW, scrollH); + filterScroll.guiLeft = scrollX; + filterScroll.guiTop = scrollTopY; + filterScroll.multipleSelection = true; + filterScroll.setSelectedList(GuiNpcMobSpawner.tagFilters); + addScroll(filterScroll); + + addTextField(new GuiNpcTextField(2, this, fontRendererObj, + scrollX, scrollTopY + scrollH + gap, scrollW, btnH, GuiNpcMobSpawner.tagSearch)); + + // Settings column + int col2X = scrollX + scrollW + gap * 4; + int controlW = 90; + int controlX = col2X + 80; + int rowH = 28; + int rowY = scrollTopY; + + addLabel(new GuiNpcLabel(2, StatCollector.translateToLocal("cloner.tagVisibility"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(12, controlX, rowY, controlW, btnH, + new String[]{"display.show", "display.all", "display.hide"}, GuiNpcMobSpawner.displayTags)); + + rowY += rowH; + addLabel(new GuiNpcLabel(3, StatCollector.translateToLocal("filter.contains"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(13, controlX, rowY, controlW, btnH, + new String[]{"filter.any", "filter.all", "filter.notany", "filter.notall"}, GuiNpcMobSpawner.filterCondition)); + + rowY += rowH + 4; + addButton(new GuiNpcButton(11, col2X, rowY, controlW + 80, btnH, "gui.deselectAll")); + + rowY += rowH + 12; + addLabel(new GuiNpcLabel(4, StatCollector.translateToLocal("cloner.order"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(14, controlX, rowY, controlW, btnH, + new String[]{"cloner.ascending", "cloner.descending"}, GuiNpcMobSpawner.ascending)); + + rowY += rowH; + addLabel(new GuiNpcLabel(5, StatCollector.translateToLocal("cloner.type"), + col2X, rowY + 5, 0xFFFFFF)); + addButton(new GuiNpcButton(15, controlX, rowY, controlW, btnH, + new String[]{"cloner.name", "cloner.date"}, GuiNpcMobSpawner.sortType)); + + filterScroll.setList(getTagList()); + } + + // ==================== CLONE / ENTITY DISPLAY ==================== + private void showClones() { + if (GuiNpcMobSpawner.activeFolder != null) { + showFolderClones(); + return; + } + + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneTagListPacket(GuiNpcMobSpawner.activeTab)); + PacketClient.sendClient(new CloneListPacket(GuiNpcMobSpawner.activeTab)); + return; + } + + if (GuiNpcMobSpawner.sortType == 0) { + this.list = ClientCloneController.Instance.getClones(GuiNpcMobSpawner.activeTab); + } else { + this.list = ClientCloneController.Instance.getClonesDate(GuiNpcMobSpawner.activeTab); + } + + this.tagMap = ClientTagMapController.Instance.getTagMap(GuiNpcMobSpawner.activeTab); + populateRawListWithTags(); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + + private void showFolderClones() { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneTagListPacket(GuiNpcMobSpawner.activeFolder)); + PacketClient.sendClient(new CloneListPacket(GuiNpcMobSpawner.activeFolder)); + return; + } + + if (ClientCloneController.Instance != null) { + if (GuiNpcMobSpawner.sortType == 0) { + this.list = ClientCloneController.Instance.getClones(GuiNpcMobSpawner.activeFolder); + } else { + this.list = ClientCloneController.Instance.getClonesDate(GuiNpcMobSpawner.activeFolder); + } + this.tagMap = ClientTagMapController.Instance.getTagMap(GuiNpcMobSpawner.activeFolder); + } else { + this.list = new ArrayList<>(); + this.tagMap = null; + } + + populateRawListWithTags(); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + + private void showEntities() { + Map data = EntityList.stringToClassMapping; + ArrayList list = new ArrayList(); + for (Object name : data.keySet()) { + Class c = (Class) data.get(name); + try { + if (EntityLiving.class.isAssignableFrom(c) + && c.getConstructor(new Class[]{World.class}) != null + && !Modifier.isAbstract(c.getModifiers())) + list.add(name.toString()); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + } + } + this.list = list; + this.rawList = new ArrayList(this.list); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + + private void populateRawListWithTags() { + this.rawList = new ArrayList<>(this.list); + if (this.tagMap != null) { + if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { + for (int i = 0; i < this.list.size(); i++) { + StringBuilder npcName = new StringBuilder(list.get(i)); + if (this.tagMap.hasClone(list.get(i))) { + for (UUID tagUUID : this.tagMap.getUUIDsList(list.get(i))) { + Tag tag = GuiNpcMobSpawner.tags.get(tagUUID); + if (tag != null) { + if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { + npcName.append(" [" + tag.name + "]"); + } + } + } + } + this.rawList.set(i, npcName.toString()); + } + } + } + } + + private NBTTagCompound getCompound() { + String sel = scroll.getSelected(); + if (sel == null) + return null; + + if (GuiNpcMobSpawner.showingClones == 0) { + if (GuiNpcMobSpawner.activeFolder != null && ClientCloneController.Instance != null) { + return ClientCloneController.Instance.getCloneData(player, sel, GuiNpcMobSpawner.activeFolder); + } + return ClientCloneController.Instance.getCloneData(player, sel, GuiNpcMobSpawner.activeTab); + } else { + Entity entity = EntityList.createEntityByName(sel, Minecraft.getMinecraft().theWorld); + if (entity == null) + return null; + NBTTagCompound compound = new NBTTagCompound(); + entity.writeToNBTOptional(compound); + return compound; + } + } + + // ==================== SEARCH / FILTER ==================== + private List getSearchList() { + if (this.list == null) { + this.list = new ArrayList(); + } + if (this.rawList == null) { + this.rawList = new ArrayList(); + } + + if (GuiNpcMobSpawner.tagFilters.size() == 0 || GuiNpcMobSpawner.showingClones == 1) { + if (GuiNpcMobSpawner.search.isEmpty()) + return new ArrayList(this.list); + else { + List list = new ArrayList(); + for (int i = 0; i < this.list.size(); i++) { + if (this.rawList.get(i).toLowerCase().contains(GuiNpcMobSpawner.search)) { + list.add(this.list.get(i)); + } + } + return list; + } + } + + if (GuiNpcMobSpawner.search.isEmpty()) { + List list = new ArrayList(); + for (String name : this.list) { + if (tagMap.hasClone(name)) { + if (meetsCondition(name)) { + list.add(name); + } + } + } + return list; + } + + List list = new ArrayList(); + for (int i = 0; i < this.list.size(); i++) { + if (this.rawList.get(i).toLowerCase().contains(GuiNpcMobSpawner.search)) { + String npcName = this.list.get(i); + if (tagMap.hasClone(npcName)) { + if (meetsCondition(npcName)) { + list.add(npcName); + } + } + } + } + return list; + } + + private boolean meetsCondition(String name) { + if (tagMap == null) { + return true; + } + boolean conditionMet = true; + boolean allRequirement = GuiNpcMobSpawner.filterCondition == 1 || GuiNpcMobSpawner.filterCondition == 3; + + for (String tagName : GuiNpcMobSpawner.tagFilters) { + UUID tagUUID = GuiNpcMobSpawner.tagNames.get(tagName); + if (tagUUID != null) { + boolean hasTag = tagMap.hasTag(name, tagUUID); + if (!allRequirement) { + if (!hasTag && GuiNpcMobSpawner.filterCondition == 0) { + conditionMet = false; + break; + } else if (hasTag && GuiNpcMobSpawner.filterCondition == 2) { + conditionMet = false; + break; + } + } else { + if (!hasTag && GuiNpcMobSpawner.filterCondition == 1) { + conditionMet = false; + break; + } else if (hasTag && GuiNpcMobSpawner.filterCondition == 3) { + conditionMet = false; + break; + } + } + } + } + return conditionMet; + } + + private List getTagList() { + if (this.tagList == null) { + this.tagList = new ArrayList(); + } + if (GuiNpcMobSpawner.tagSearch.isEmpty()) + return new ArrayList(GuiNpcMobSpawner.tagNames.keySet()); + + List list = new ArrayList(); + for (String name : this.tagList) { + if (name.toLowerCase().contains(GuiNpcMobSpawner.tagSearch)) + list.add(name); + } + return list; + } + + // ==================== SCROLL EVENTS ==================== + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + // Phase 2: ignore clicks on the center clone scroll + if (guiCustomScroll.id == 0 && movePhase == 2) { + return; + } + + if (guiCustomScroll.id == 0 && movePhase == 1) { + moveSelection = scroll.getSelectedList(); + GuiNpcButton confirmBtn = getButton(51); + if (confirmBtn != null) { + confirmBtn.enabled = !moveSelection.isEmpty(); + } + return; + } + + if (guiCustomScroll.id == 2) { + String selected = navScroll.getSelected(); + if (selected == null) return; + + if (movePhase == 2) { + // Cannot move to the same location + if (selected.equals(getNavSelection())) { + return; + } + // Selecting destination from nav + if (selected.startsWith("Tab ")) { + try { + int tabNum = Integer.parseInt(selected.substring(4)); + setSubGui(new SubGuiMoveConfirm(moveSelection.size(), tabNum, null)); + } catch (NumberFormatException ignored) { + } + } else { + setSubGui(new SubGuiMoveConfirm(moveSelection.size(), -1, selected)); + } + return; + } + + if (movePhase == 1) { + movePhase = 0; + moveSelection.clear(); + } + + handleNavClick(selected); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + } + + // ==================== KEYBOARD ==================== + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + + GuiNpcTextField searchField = getTextField(1); + if (searchField != null) { + String newText = searchField.getText().toLowerCase(); + if (!GuiNpcMobSpawner.search.equals(newText)) { + GuiNpcMobSpawner.search = newText; + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + } + + GuiNpcTextField tagSearchField = getTextField(2); + if (tagSearchField != null) { + String newText = tagSearchField.getText().toLowerCase(); + if (!GuiNpcMobSpawner.tagSearch.equals(newText)) { + GuiNpcMobSpawner.tagSearch = newText; + filterScroll.setList(getTagList()); + } + } + + GuiNpcTextField navSearchField = getTextField(3); + if (navSearchField != null) { + String newNavSearch = navSearchField.getText().toLowerCase(); + if (!navSearch.equals(newNavSearch)) { + navSearch = newNavSearch; + buildNavList(); + navScroll.setListWithIcons(navNames, navIcons); + navScroll.setSelected(getNavSelection()); + } + } + } + + // ==================== BUTTON ACTIONS ==================== + @Override + protected void actionPerformed(GuiButton guibutton) { + int id = guibutton.id; + + if (id == 3) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 0; + loadFolderNames(); + initGui(); + } + if (id == 4) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 1; + initGui(); + } + if (id == 5) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 2; + PacketClient.sendClient(new CloneFolderListPacket()); + initGui(); + } + if (id == 16) { + movePhase = 0; + moveSelection.clear(); + GuiNpcMobSpawner.savedContentScrollY = 0; + GuiNpcMobSpawner.savedNavScrollY = 0; + GuiNpcMobSpawner.showingClones = 3; + initGui(); + } + if (id == 17) { + close(); + } + + // Minimize — return to normal GUI + if (id == 61) { + GuiNpcMobSpawner.isFullscreen = false; + Minecraft.getMinecraft().displayGuiScreen( + new GuiNpcMobSpawner(posX, posY, posZ)); + } + + // Spawn + if (id == 1) { + if (GuiNpcMobSpawner.showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + if (GuiNpcMobSpawner.activeFolder != null) + SpawnMobPacket.ServerFolder(posX, posY, posZ, sel, GuiNpcMobSpawner.activeFolder); + else + SpawnMobPacket.Server(posX, posY, posZ, sel, GuiNpcMobSpawner.activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + SpawnMobPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Mob Spawner + if (id == 2) { + if (GuiNpcMobSpawner.showingClones == 2) { + String sel = scroll.getSelected(); + if (sel == null) return; + if (GuiNpcMobSpawner.activeFolder != null) + MobSpawnerPacket.ServerFolder(posX, posY, posZ, sel, GuiNpcMobSpawner.activeFolder); + else + MobSpawnerPacket.Server(posX, posY, posZ, sel, GuiNpcMobSpawner.activeTab); + close(); + } else { + NBTTagCompound compound = getCompound(); + if (compound == null) return; + MobSpawnerPacket.Client(posX, posY, posZ, compound); + close(); + } + } + + // Remove + if (id == 6) { + if (scroll.getSelected() != null) { + int prevSelected = scroll.selected; + if (GuiNpcMobSpawner.showingClones == 2) { + if (GuiNpcMobSpawner.activeFolder != null) + PacketClient.sendClient(new CloneRemovePacket(GuiNpcMobSpawner.activeFolder, scroll.getSelected())); + else + PacketClient.sendClient(new CloneRemovePacket(GuiNpcMobSpawner.activeTab, scroll.getSelected())); + return; + } + if (GuiNpcMobSpawner.activeFolder != null && ClientCloneController.Instance != null) + ClientCloneController.Instance.removeClone(scroll.getSelected(), GuiNpcMobSpawner.activeFolder); + else + ClientCloneController.Instance.removeClone(scroll.getSelected(), GuiNpcMobSpawner.activeTab); + initGui(); + if (scroll.list != null && !scroll.list.isEmpty()) { + scroll.selected = Math.min(prevSelected, scroll.list.size() - 1); + } else { + scroll.selected = -1; + } + } + } + + // Move toggle + if (id == 50) { + if (movePhase == 0) { + movePhase = 1; + moveSelection.clear(); + } else { + movePhase = 0; + moveSelection.clear(); + } + initGui(); + } + // Confirm move selection + if (id == 51) { + if (movePhase == 1 && !moveSelection.isEmpty()) { + movePhase = 2; + initGui(); + } + } + + // Filter controls + if (id == 11) { + GuiNpcMobSpawner.tagFilters = new HashSet<>(); + filterScroll.setSelectedList(GuiNpcMobSpawner.tagFilters); + initGui(); + } + if (id == 12) { + GuiNpcMobSpawner.displayTags = (byte) ((GuiNpcButton) guibutton).getValue(); + } + if (id == 13) { + GuiNpcMobSpawner.filterCondition = (byte) ((GuiNpcButton) guibutton).getValue(); + } + if (id == 14) { + GuiNpcMobSpawner.ascending = (byte) ((GuiNpcButton) guibutton).getValue(); + } + if (id == 15) { + GuiNpcMobSpawner.sortType = (byte) ((GuiNpcButton) guibutton).getValue(); + } + + // Create folder + if (id == 40) { + setSubGui(new SubGuiCloneFolderName("")); + } + // Rename folder + if (id == 41) { + if (GuiNpcMobSpawner.activeFolder != null) + setSubGui(new SubGuiCloneFolderName(GuiNpcMobSpawner.activeFolder)); + } + // Delete folder + if (id == 42) { + if (GuiNpcMobSpawner.activeFolder != null) { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderCrudPacket( + CloneFolderCrudPacket.ACTION_DELETE, GuiNpcMobSpawner.activeFolder)); + } else if (ClientCloneController.Instance != null) { + ClientCloneController.Instance.deleteFolder(GuiNpcMobSpawner.activeFolder); + loadFolderNames(); + } + GuiNpcMobSpawner.activeFolder = null; + GuiNpcMobSpawner.activeTab = 1; + initGui(); + } + } + } + + // ==================== SUB GUI ==================== + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiCloneFolderName) { + SubGuiCloneFolderName folderGui = (SubGuiCloneFolderName) subgui; + if (folderGui.cancelled) return; + + String newName = folderGui.getFolderName(); + if (newName == null || newName.isEmpty()) return; + + if (folderGui.isRename()) { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderCrudPacket( + CloneFolderCrudPacket.ACTION_RENAME, folderGui.getOriginalName(), newName)); + } else if (ClientCloneController.Instance != null) { + ClientCloneController.Instance.renameFolder(folderGui.getOriginalName(), newName); + loadFolderNames(); + } + GuiNpcMobSpawner.activeFolder = newName; + GuiNpcMobSpawner.activeTab = -1; + } else { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneFolderCrudPacket( + CloneFolderCrudPacket.ACTION_CREATE, newName)); + } else if (ClientCloneController.Instance != null) { + ClientCloneController.Instance.createFolder(newName); + loadFolderNames(); + } + GuiNpcMobSpawner.activeFolder = newName; + GuiNpcMobSpawner.activeTab = -1; + } + initGui(); + } + + if (subgui instanceof SubGuiMoveConfirm) { + SubGuiMoveConfirm confirm = (SubGuiMoveConfirm) subgui; + if (confirm.confirmed && !moveSelection.isEmpty()) { + int fromTab = GuiNpcMobSpawner.activeFolder != null ? -1 : GuiNpcMobSpawner.activeTab; + String fromFolder = GuiNpcMobSpawner.activeFolder; + int toTab = confirm.destTab; + String toFolder = confirm.destFolder; + + for (String cloneName : moveSelection) { + if (GuiNpcMobSpawner.showingClones == 2) { + PacketClient.sendClient(new CloneMovePacket( + cloneName, fromTab, fromFolder, toTab, toFolder)); + } else if (ClientCloneController.Instance != null) { + if (fromFolder != null && toFolder != null) { + ClientCloneController.Instance.moveClone(cloneName, fromFolder, toFolder); + } else if (fromFolder != null) { + ClientCloneController.Instance.moveClone(cloneName, fromFolder, toTab); + } else if (toFolder != null) { + ClientCloneController.Instance.moveClone(cloneName, fromTab, toFolder); + } else { + ClientCloneController.Instance.moveClone(cloneName, fromTab, toTab); + } + } + } + } + movePhase = 0; + moveSelection.clear(); + initGui(); + } + } + + // ==================== DATA FROM SERVER ==================== + @Override + public void save() { + } + + @Override + public void setGuiData(NBTTagCompound compound) { + if (compound.hasKey("CloneFolders")) { + NBTTagList folderList = compound.getTagList("CloneFolders", 10); + folderNames.clear(); + for (int i = 0; i < folderList.tagCount(); i++) { + CloneFolder folder = new CloneFolder(); + folder.readNBT(folderList.getCompoundTagAt(i)); + folderNames.add(folder.name); + } + initGui(); + } else if (compound.hasKey("MoveSuccess")) { + initGui(); + } else if (compound.hasKey("CloneTags")) { + if (GuiNpcMobSpawner.activeFolder != null) { + this.tagMap = new TagMap(GuiNpcMobSpawner.activeFolder); + } else { + this.tagMap = new TagMap(GuiNpcMobSpawner.activeTab); + } + NBTTagCompound cloneTags = compound.getCompoundTag("CloneTags"); + this.tagMap.readNBT(cloneTags); + } else if (compound.hasKey("AllTags")) { + NBTTagList validTags = compound.getTagList("AllTags", 10); + if (validTags != null) { + HashMap tagsUpdate = new HashMap<>(); + HashMap tagNamesUpdate = new HashMap<>(); + for (int j = 0; j < validTags.tagCount(); j++) { + NBTTagCompound tagStructure = validTags.getCompoundTagAt(j); + Tag tag = new Tag(); + tag.readNBT(tagStructure); + tagsUpdate.put(tag.uuid, tag); + tagNamesUpdate.put(tag.name, tag.uuid); + } + GuiNpcMobSpawner.tags = tagsUpdate; + GuiNpcMobSpawner.tagNames = tagNamesUpdate; + this.tagList = new ArrayList(GuiNpcMobSpawner.tagNames.keySet()); + filterScroll.setList(getTagList()); + } + } else { + List list = new ArrayList(); + if (GuiNpcMobSpawner.sortType == 1) { + NBTTagList nbtlist = compound.getTagList("ListDate", 8); + for (int i = 0; i < nbtlist.tagCount(); i++) { + list.add(nbtlist.getStringTagAt(i)); + } + } else { + NBTTagList nbtlist = compound.getTagList("List", 8); + for (int i = 0; i < nbtlist.tagCount(); i++) { + list.add(nbtlist.getStringTagAt(i)); + } + } + + this.list = list; + populateRawListWithTags(); + scroll.setList(getSearchList(), GuiNpcMobSpawner.ascending == 0, GuiNpcMobSpawner.sortType == 0); + } + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiCloneFolderName.java b/src/main/java/noppes/npcs/client/gui/SubGuiCloneFolderName.java new file mode 100644 index 000000000..508b00518 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiCloneFolderName.java @@ -0,0 +1,67 @@ +package noppes.npcs.client.gui; + +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.SubGuiInterface; +import noppes.npcs.controllers.data.CloneFolder; + +public class SubGuiCloneFolderName extends SubGuiInterface { + private String originalName; + public boolean cancelled = true; + private String folderName = ""; + + public SubGuiCloneFolderName(String existingName) { + this.originalName = existingName; + this.folderName = existingName; + xSize = 200; + ySize = 80; + this.closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + String title = isRename() ? "Rename Folder" : "New Folder"; + addLabel(new GuiNpcLabel(0, title, guiLeft + 5, guiTop + 5)); + addTextField(new GuiNpcTextField(0, this, fontRendererObj, guiLeft + 5, guiTop + 20, 190, 20, folderName)); + + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 50, 90, 20, "gui.done")); + addButton(new GuiNpcButton(1, guiLeft + 100, guiTop + 50, 90, 20, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 0) { + // Done + folderName = getTextField(0).getText().trim(); + if (CloneFolder.isValidName(folderName)) { + cancelled = false; + close(); + } + } + if (guibutton.id == 1) { + // Cancel + cancelled = true; + close(); + } + } + + public boolean isRename() { + return originalName != null && !originalName.isEmpty(); + } + + public String getFolderName() { + return folderName; + } + + public String getOriginalName() { + return originalName; + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiFolderSelect.java b/src/main/java/noppes/npcs/client/gui/SubGuiFolderSelect.java new file mode 100644 index 000000000..3ec727543 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiFolderSelect.java @@ -0,0 +1,74 @@ +package noppes.npcs.client.gui; + +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +public class SubGuiFolderSelect extends SubGuiInterface implements ICustomScrollListener { + + public String selectedFolder; + private final List folderList; + private GuiCustomScroll folderScroll; + + public SubGuiFolderSelect(List folders, String currentSelection) { + this.folderList = new ArrayList<>(folders); + this.selectedFolder = currentSelection; + setBackground("menubg.png"); + xSize = 200; + ySize = 220; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + folderScroll = new GuiCustomScroll(this, 0); + folderScroll.setSize(xSize - 8, ySize - 50); + folderScroll.guiLeft = guiLeft + 4; + folderScroll.guiTop = guiTop + 4; + folderScroll.setList(new ArrayList<>(folderList)); + if (selectedFolder != null) { + folderScroll.setSelected(selectedFolder); + } + addScroll(folderScroll); + + int btnW = (xSize - 12) / 2; + addButton(new GuiNpcButton(0, guiLeft + 4, guiTop + ySize - 44, btnW, 20, "gui.done")); + addButton(new GuiNpcButton(1, guiLeft + 4 + btnW + 4, guiTop + ySize - 44, btnW, 20, "gui.cancel")); + + getButton(0).enabled = folderScroll.hasSelected(); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + getButton(0).enabled = folderScroll.hasSelected(); + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + selectedFolder = selection; + close(); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 0) { + selectedFolder = folderScroll.getSelected(); + close(); + } + if (guibutton.id == 1) { + selectedFolder = null; + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/SubGuiMoveConfirm.java b/src/main/java/noppes/npcs/client/gui/SubGuiMoveConfirm.java new file mode 100644 index 000000000..ee70367f7 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/SubGuiMoveConfirm.java @@ -0,0 +1,57 @@ +package noppes.npcs.client.gui; + +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; + +public class SubGuiMoveConfirm extends SubGuiInterface { + public boolean confirmed = false; + + private final int count; + public final int destTab; + public final String destFolder; + + public SubGuiMoveConfirm(int count, int destTab, String destFolder) { + this.count = count; + this.destTab = destTab; + this.destFolder = destFolder; + xSize = 220; + ySize = 90; + closeOnEsc = true; + } + + @Override + public void initGui() { + super.initGui(); + + String line1 = "Move " + count + " clone" + (count != 1 ? "s" : "") + " to:"; + addLabel(new GuiNpcLabel(0, line1, guiLeft + 10, guiTop + 10, 0xFFFFFF)); + + String dest; + if (destFolder != null) { + dest = "Folder: \"" + destFolder + "\""; + } else { + dest = "Tab: " + destTab; + } + addLabel(new GuiNpcLabel(1, " " + dest, guiLeft + 10, guiTop + 25, 0xFFFFFF)); + + addButton(new GuiNpcButton(0, guiLeft + 10, guiTop + 55, 95, 20, "gui.yes")); + addButton(new GuiNpcButton(1, guiLeft + 115, guiTop + 55, 95, 20, "gui.cancel")); + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + if (guibutton.id == 0) { + confirmed = true; + close(); + } + if (guibutton.id == 1) { + close(); + } + } + + @Override + public void save() { + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java index 59046ef77..7bc5c3846 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/GuiNPCAbilities.java @@ -3,10 +3,14 @@ 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.controllers.data.ability.AbilityVariant; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket; import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; +import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket; +import kamkeel.npcs.util.Register; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import net.minecraft.nbt.NBTTagCompound; @@ -26,11 +30,7 @@ import noppes.npcs.client.gui.util.SubGuiInterface; import noppes.npcs.constants.EnumScrollData; import noppes.npcs.entity.EntityNPCInterface; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import java.util.Vector; +import java.util.*; /** * GUI for managing NPC abilities. @@ -43,6 +43,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // All available ability types (typeId -> index) private final HashMap allAbilityTypes = new HashMap<>(); + private final HashMap filteredAbilityTypes = new HashMap<>(); // Display name to typeId mapping for the available types scroll private final HashMap displayNameToTypeId = new HashMap<>(); @@ -58,10 +59,42 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC private String search = ""; private int selectedAbilityIndex = -1; + // Existing preset names for duplicate checking + private final Set existingPresetNames = new HashSet<>(); + + // Pending variant selection + private String pendingTypeId = null; + + public static int modIndex = 0; + public static ScrollType scrollType = ScrollType.CNPC; + public GuiNPCAbilities(EntityNPCInterface npc) { super(npc); PacketClient.sendClient(new AbilitiesGetAllPacket()); PacketClient.sendClient(new AbilitiesNpcGetPacket()); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + } + + public enum ScrollType { + CNPC, + MODDED, + ALL; + + @Override + public String toString() { + switch (this) { + case CNPC: return "CustomNPCs"; + case MODDED: + if (Register.isEmpty("ability")) + return "modded"; + + String namespace = Register.REGISTERED_NAMESPACES.get("ability").get(modIndex); + String displayName = Register.NAMESPACE_DISPLAY_NAMES.get(namespace); + return displayName != null ? displayName : namespace; + case ALL: return "filter.all"; + default: return name(); + } + } } @Override @@ -70,25 +103,27 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC int y = guiTop + 10; - // Enabled checkbox - 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)); + addButton(new GuiNpcButton(50, guiLeft + 5, y, 140, 20, scrollType.toString())); // 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); + addLabel(new GuiNpcLabel(101, "ability.minCooldown", guiLeft + 210, y + 5)); + GuiNpcTextField minField = new GuiNpcTextField(101, this, fontRendererObj, guiLeft + 260, 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); + addLabel(new GuiNpcLabel(102, "ability.maxCooldown", guiLeft + 320, y + 5)); + GuiNpcTextField maxField = new GuiNpcTextField(102, this, fontRendererObj, guiLeft + 370, y, 40, 20, "" + maxCooldown); maxField.setIntegersOnly(); maxField.setMinMaxDefault(0, 10000, 60); addTextField(maxField); y += 28; + // Enabled checkbox + addButton(new GuiNpcButton(100, guiLeft + 334, y + 145, 76, 20, new String[]{"gui.disabled", "gui.enabled"}, abilitiesEnabled ? 1 : 0)); + getButton(100).packedFGColour = abilitiesEnabled ? 0x00FF00 : 0xFF0000; + // Left scroll: available ability types addLabel(new GuiNpcLabel(1, "ability.availableTypes", guiLeft + 5, y)); if (availableTypesScroll == null) { @@ -107,9 +142,9 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC addLabel(new GuiNpcLabel(2, "ability.npcAbilities", guiLeft + 210, y)); if (npcAbilitiesScroll == null) { npcAbilitiesScroll = new GuiCustomScroll(this, 1); - npcAbilitiesScroll.setSize(160, 130); + npcAbilitiesScroll.setSize(200, 130); } else { - npcAbilitiesScroll.setSize(160, 130); + npcAbilitiesScroll.setSize(200, 130); } npcAbilitiesScroll.guiLeft = guiLeft + 210; npcAbilitiesScroll.guiTop = y + 12; @@ -118,11 +153,12 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Center buttons: Add/Remove int centerX = guiLeft + 158; - addButton(new GuiNpcButton(70, centerX, y + 40, 40, 20, ">>>")); // Add - addButton(new GuiNpcButton(71, centerX, y + 62, 40, 20, "<<<")); // Remove + addButton(new GuiNpcButton(70, centerX, y + 15, 40, 20, ">>>")); // Add + addButton(new GuiNpcButton(71, centerX, y + 37, 40, 20, "<<<")); // Remove + getButton(71).setEnabled(selectedAbilityIndex >= 0); // Load button (under the add/remove arrows) - addButton(new GuiNpcButton(75, centerX, y + 90, 40, 20, "gui.load")); + addButton(new GuiNpcButton(75, centerX, y + 60, 40, 20, "gui.load")); // On/Off toggle for selected ability (under Load button) if (selectedAbilityIndex >= 0 && selectedAbilityIndex < npcSlots.size()) { @@ -143,7 +179,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC 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")); + addButton(new GuiNpcButton(76, centerX, y + 82, 40, 20, "gui.save")); getButton(76).setEnabled(selectedAbilityIndex >= 0); } @@ -154,6 +190,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC // Enabled toggle if (id == 100) { abilitiesEnabled = ((GuiNpcButton) guibutton).getValue() == 1; + initGui(); save(); return; } @@ -164,8 +201,17 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC String displayName = availableTypesScroll.getSelected(); String typeId = displayNameToTypeId.get(displayName); if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return; + } Ability newAbility = AbilityController.Instance.create(typeId); if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } newAbility.setId(UUID.randomUUID().toString()); npcSlots.add(AbilitySlot.inline(newAbility)); selectedAbilityIndex = npcSlots.size() - 1; @@ -252,7 +298,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (abilityToSave.getName() == null || abilityToSave.getName().isEmpty()) { setSubGui(abilityToSave.createConfigGui(this)); } else { - setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave)); + setSubGui(new SubGuiAbilitySaveConfirm(abilityToSave, null, existingPresetNames)); } } } @@ -274,6 +320,40 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC return; } + if (id == 50) { + if (scrollType != ScrollType.MODDED) { + ScrollType[] values = ScrollType.values(); + ScrollType next = values[(scrollType.ordinal() + 1) % values.length]; + // Skip MODDED if no namespaces are registered + if (next == ScrollType.MODDED && Register.isEmpty("ability")) { + next = ScrollType.ALL; + } + scrollType = next; + } else { + List list = Register.REGISTERED_NAMESPACES.get("ability"); + + if (list != null && !list.isEmpty()) { + if (modIndex == list.size() - 1) { + scrollType = ScrollType.ALL; + } else { + modIndex = (modIndex + 1) % list.size(); + } + } else { + modIndex = 0; + scrollType = ScrollType.ALL; + } + } + + Map dummyMap = new HashMap<>(allAbilityTypes); + filteredAbilityTypes.clear(); + filteredAbilityTypes.putAll(getFilteredData(dummyMap)); + + // Reset scroll position when changing category + if (availableTypesScroll != null) { + availableTypesScroll.resetScroll(); + } + } + initGui(); } @@ -282,9 +362,21 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC if (type == EnumScrollData.ABILITY_TYPES) { allAbilityTypes.clear(); allAbilityTypes.putAll(data); + + filteredAbilityTypes.putAll(getFilteredData(allAbilityTypes)); if (availableTypesScroll != null) { availableTypesScroll.setList(getFilteredTypeList()); } + } else if (type == EnumScrollData.CUSTOM_ABILITIES) { + existingPresetNames.clear(); + for (String key : data.keySet()) { + int tabIndex = key.indexOf('\t'); + if (tabIndex > 0) { + existingPresetNames.add(key.substring(0, tabIndex)); + } else { + existingPresetNames.add(key); + } + } } initGui(); } @@ -340,10 +432,35 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC } } + private HashMap getFilteredData(Map data) { + HashMap filteredData = new HashMap<>(); + if (scrollType == ScrollType.CNPC) { + data.entrySet().stream() + .filter(e -> e.getKey().startsWith("ability.cnpc.")) + .forEach(e -> filteredData.put(e.getKey(), e.getValue())); + } else if (scrollType == ScrollType.MODDED) { + if (!Register.isEmpty("ability")) { + List registerList = Register.REGISTERED_NAMESPACES.get("ability"); + + if (!registerList.isEmpty()) { + String namespace = registerList.get(modIndex); + + data.entrySet().stream() + .filter(e -> e.getKey().startsWith("ability." + namespace + ".")) + .forEach(e -> filteredData.put(e.getKey(), e.getValue())); + } + } + } else { + filteredData.putAll(data); + } + + return filteredData; + } + private List getFilteredTypeList() { List list = new ArrayList<>(); displayNameToTypeId.clear(); - for (String typeId : allAbilityTypes.keySet()) { + for (String typeId : filteredAbilityTypes.keySet()) { String displayName = I18n.format(typeId); // Search matches either the display name or the typeId if (search.isEmpty() || displayName.toLowerCase().contains(search) || typeId.toLowerCase().contains(search)) { @@ -529,7 +646,24 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC @Override public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiAbilityEditMode) { + if (subgui instanceof SubGuiAbilityVariantSelect) { + SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui; + int idx = variantGui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + variantGui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + npcSlots.add(AbilitySlot.inline(newAbility)); + selectedAbilityIndex = npcSlots.size() - 1; + updateNpcAbilitiesList(); + selectAbilityByIndex(selectedAbilityIndex); + save(); + } + } + pendingTypeId = null; + initGui(); + } else if (subgui instanceof SubGuiAbilityEditMode) { int mode = ((SubGuiAbilityEditMode) subgui).getResult(); if (mode < 0) return; // cancelled @@ -568,7 +702,7 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC AbilitySlot slot = npcSlots.get(selectedAbilityIndex); if (slot.isReference()) { // For reference slots, save back to controller - // (The resolved copy was edited in-place) + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); } else { // For inline slots, replace with the updated ability npcSlots.set(selectedAbilityIndex, AbilitySlot.inline(ability)); diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index 611f8c918..bcfce7687 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -2,22 +2,16 @@ package noppes.npcs.client.gui.advanced; import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.Condition; -import kamkeel.npcs.controllers.data.ability.LockMovementType; -import kamkeel.npcs.controllers.data.ability.TargetingMode; -import kamkeel.npcs.controllers.data.telegraph.TelegraphType; -import noppes.npcs.controllers.data.Animation; -import noppes.npcs.controllers.data.Frame; -import noppes.npcs.controllers.AnimationController; +import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldBuilder; +import noppes.npcs.client.gui.builder.FieldDef; import net.minecraft.client.gui.GuiButton; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; -import noppes.npcs.client.gui.SubGuiColorSelector; -import noppes.npcs.client.gui.select.GuiAnimationSelection; -import noppes.npcs.client.gui.select.GuiSoundSelection; 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.GuiNpcTextField; +import noppes.npcs.client.gui.util.GuiScrollWindow; import noppes.npcs.client.gui.util.IAbilityConfigCallback; import noppes.npcs.client.gui.util.ISubGuiListener; import noppes.npcs.client.gui.util.ITextfieldListener; @@ -26,152 +20,96 @@ import noppes.npcs.client.gui.util.SubGuiInterface; import java.util.ArrayList; import java.util.List; -/** - * Base SubGui for editing ability configuration with tabbed interface. - * Uses GuiMenuTopButton for navigation tabs. - *

- * Tabs: - * - General: Name, Weight, Lock Movement, Interruptible, Timing - * - Type: Type-specific settings per Ability (override in subclasses) - * - Target: Min/Max Range, Targeting Mode, Conditions (up to 3) - * - Effects: Sounds, Animations, Telegraph settings, Colors - *

- * Subclasses should override initTypeTab() and handleTypeButton()/handleTypeTextField() - * to provide type-specific settings UI. - */ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldListener, ISubGuiListener { - // Tab constants - protected static final int TAB_GENERAL = 0; - protected static final int TAB_TYPE = 1; - protected static final int TAB_TARGET = 2; - protected static final int TAB_EFFECTS = 3; - protected static final int TAB_VISUAL = 4; + private static final int DECLARATIVE_ID_START = 1000; + private static final int CLEAR_ID_START = 2000; + private static final int LABEL_ID_START = 3000; - // Core references - protected final Ability ability; - protected final IAbilityConfigCallback callback; - protected int activeTab = TAB_GENERAL; + // Fixed tab indices + private static final int TAB_GENERAL = 0; + private static final int TAB_TYPE = 1; + private static final int TAB_TARGET = 2; + private static final int TAB_EFFECTS = 3; + // Custom tabs start at index 4 - // ═══════════════════════════════════════════════════════════════════════════ - // CACHED VALUES - General Tab - // ═══════════════════════════════════════════════════════════════════════════ - protected String name; - protected boolean enabled; - protected int weight; - protected LockMovementType lockMovement; - protected boolean interruptible; + // Tab name strings (matching FieldDef.tab() values) + private static final String TAB_NAME_GENERAL = "General"; + private static final String TAB_NAME_TYPE = "Type"; + private static final String TAB_NAME_TARGET = "Target"; + private static final String TAB_NAME_EFFECTS = "Effects"; - // Timing - protected int cooldownTicks; - protected int windUpTicks; - protected int dazedTicks; - protected boolean syncWindupWithAnimation = true; // Sync windup ticks with animation duration + private static final int L_LABEL_X = 5; + private static final int ROW_H = 24; - // ═══════════════════════════════════════════════════════════════════════════ - // CACHED VALUES - Target Tab - // ═══════════════════════════════════════════════════════════════════════════ - protected float minRange; - protected float maxRange; - protected TargetingMode targetingMode; - protected List conditions; + private final Ability ability; + private final IAbilityConfigCallback callback; + private int activeTab = TAB_GENERAL; - // ═══════════════════════════════════════════════════════════════════════════ - // CACHED VALUES - Effects Tab - // ═══════════════════════════════════════════════════════════════════════════ - protected String windUpSound; - protected String activeSound; - protected int windUpAnimationId; - protected int activeAnimationId; - protected String windUpAnimationName = null; - protected String activeAnimationName = null; + private List fieldDefs; + private List customTabNames; - // Telegraph - protected boolean showTelegraph; - protected int windUpColor; - protected int activeColor; + private List conditions; + private int editingConditionIndex = -1; - // Editing state - protected int editingColorId = 0; - protected int editingSoundId = 0; - protected int editingAnimationId = 0; - protected int editingConditionIndex = -1; + private AbilityFieldBuilder builder; - // ═══════════════════════════════════════════════════════════════════════════ - // ABILITY TYPE FEATURES - // ═══════════════════════════════════════════════════════════════════════════ - protected final boolean supportsTelegraph; - protected final boolean targetingModeLocked; - protected final boolean hasTypeSettings; - protected final boolean hasVisualSettings; + // Scroll position preservation per tab + private float[] tabScrollY; public SubGuiAbilityConfig(Ability ability, IAbilityConfigCallback callback) { this.ability = ability; this.callback = callback; - - // Cache values from ability - General - this.name = ability.getName() != null ? ability.getName() : ""; - this.enabled = ability.isEnabled(); - this.weight = ability.getWeight(); - this.lockMovement = ability.getLockMovement(); - this.interruptible = ability.isInterruptible(); - - // Timing - this.cooldownTicks = ability.getCooldownTicks(); - this.windUpTicks = ability.getWindUpTicks(); - this.dazedTicks = ability.getDazedTicks(); - - // Target - this.minRange = ability.getMinRange(); - this.maxRange = ability.getMaxRange(); - this.targetingMode = ability.getTargetingMode(); this.conditions = new ArrayList<>(ability.getConditions()); - // Effects - this.windUpSound = ability.getWindUpSound(); - this.activeSound = ability.getActiveSound(); - // Animation: check name first (built-in), then ID (user) - this.windUpAnimationName = ability.getWindUpAnimationName(); - this.activeAnimationName = ability.getActiveAnimationName(); - this.windUpAnimationId = ability.getWindUpAnimationId(); - this.activeAnimationId = ability.getActiveAnimationId(); - - // Telegraph - this.showTelegraph = ability.isShowTelegraph(); - this.windUpColor = ability.getWindUpColor(); - this.activeColor = ability.getActiveColor(); - - // Determine ability type features - TelegraphType defaultType = ability.getTelegraphType(); - this.supportsTelegraph = defaultType != null && defaultType != TelegraphType.NONE; - this.targetingModeLocked = ability.isTargetingModeLocked(); - this.hasTypeSettings = ability.hasTypeSettings(); - this.hasVisualSettings = hasVisualSettings(); + this.fieldDefs = ability.getAllDefinitions(); + discoverCustomTabs(); setBackground("menubg.png", 217); xSize = 356; ySize = 200; } + private void discoverCustomTabs() { + customTabNames = new ArrayList<>(); + for (FieldDef def : fieldDefs) { + String tab = def.getTab(); + if (tab != null + && !TAB_NAME_GENERAL.equals(tab) + && !TAB_NAME_TYPE.equals(tab) + && !TAB_NAME_TARGET.equals(tab) + && !TAB_NAME_EFFECTS.equals(tab) + && !customTabNames.contains(tab)) { + customTabNames.add(tab); + } + } + tabScrollY = new float[4 + customTabNames.size()]; + } + + // ═══════════════════════════════════════════════════════════════════════════ + // INIT GUI + // ═══════════════════════════════════════════════════════════════════════════ + @Override public void initGui() { + // Save scroll position before super clears scroll windows + GuiScrollWindow oldSw = getScrollableGui(0); + if (oldSw != null && activeTab < tabScrollY.length) { + tabScrollY[activeTab] = oldSw.nextScrollY; + } + super.initGui(); - // ═══════════════════════════════════════════════════════════════════════ - // TOP TABS using GuiMenuTopButton - // ═══════════════════════════════════════════════════════════════════════ + // Tab buttons — always show General, Type, Target, Effects GuiMenuTopButton generalTab = new GuiMenuTopButton(90, guiLeft + 4, guiTop - 17, "menu.general"); generalTab.active = (activeTab == TAB_GENERAL); addTopButton(generalTab); - GuiMenuTopButton lastTab = generalTab; - if (hasTypeSettings) { - GuiMenuTopButton typeTab = new GuiMenuTopButton(91, lastTab, "gui.type"); - typeTab.active = (activeTab == TAB_TYPE); - addTopButton(typeTab); - lastTab = typeTab; - } + GuiMenuTopButton typeTab = new GuiMenuTopButton(91, lastTab, "gui.type"); + typeTab.active = (activeTab == TAB_TYPE); + addTopButton(typeTab); + lastTab = typeTab; GuiMenuTopButton targetTab = new GuiMenuTopButton(92, lastTab, "script.target"); targetTab.active = (activeTab == TAB_TARGET); @@ -183,277 +121,113 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi addTopButton(effectsTab); lastTab = effectsTab; - if (hasVisualSettings) { - GuiMenuTopButton visualTab = new GuiMenuTopButton(94, lastTab, "ability.tab.visual"); - visualTab.active = (activeTab == TAB_VISUAL); - addTopButton(visualTab); + // Custom tabs (Visual, etc.) + for (int i = 0; i < customTabNames.size(); i++) { + GuiMenuTopButton ct = new GuiMenuTopButton(94 + i, lastTab, customTabNames.get(i)); + ct.active = (activeTab == 4 + i); + addTopButton(ct); + lastTab = ct; } - // Close button (X) in top menu bar - use -1000 to avoid any ID conflicts GuiMenuTopButton closeBtn = new GuiMenuTopButton(-1000, guiLeft + xSize - 22, guiTop - 17, "X"); addTopButton(closeBtn); - int contentY = guiTop + 5; + // Build scroll window dimensions + int swX = guiLeft + 4; + int swY = guiTop + 5; + int swW = xSize - 8; + int swH = ySize - 10; - // ═══════════════════════════════════════════════════════════════════════ - // TAB CONTENT - // ═══════════════════════════════════════════════════════════════════════ - switch (activeTab) { - case TAB_GENERAL: - initGeneralTab(contentY); - break; - case TAB_TYPE: - initTypeTab(contentY); - break; - case TAB_TARGET: - initTargetTab(contentY); - break; - case TAB_EFFECTS: - initEffectsTab(contentY); - break; - case TAB_VISUAL: - initVisualTab(contentY); - break; - } + int y = 5; + int labelCounter = LABEL_ID_START; - // ═══════════════════════════════════════════════════════════════════════ - // BOTTOM ROW - Enabled toggle (only on General tab) - // ═══════════════════════════════════════════════════════════════════════ + // General tab: type label at top — need to reserve space before building if (activeTab == TAB_GENERAL) { - addLabel(new GuiNpcLabel(99, "gui.enabled", guiLeft + 8, guiTop + ySize - 18)); - GuiNpcButton enabledBtn = new GuiNpcButton(2, guiLeft + 55, guiTop + ySize - 24, 40, 20, new String[]{"gui.no", "gui.yes"}, enabled ? 1 : 0); - enabledBtn.setTextColor(enabled ? 0x00FF00 : 0xFF0000); - addButton(enabledBtn); + y += ROW_H; + } + + // Build declarative fields into an auto-created scroll window + List tabFields = getVisibleFieldsForTab(activeTab); + builder = new AbilityFieldBuilder(this, fontRendererObj); + builder.startIds(DECLARATIVE_ID_START, CLEAR_ID_START, labelCounter); + builder.startY(y); + + GuiScrollWindow sw = builder.buildScrollWindow(tabFields, swX, swY, swW, swH); + + // General tab: add type label at top of scroll window + if (activeTab == TAB_GENERAL) { + sw.addLabel(new GuiNpcLabel(builder.getNextLabelId(), "gui.type", 5, 5 + 5, 0xFFFFFF)); + sw.addLabel(new GuiNpcLabel(builder.getNextLabelId() + 1, ability.getTypeId(), 55, 5 + 5, 0xFFFFFF)); + } + + // Conditions on target tab — appended after field defs + if (activeTab == TAB_TARGET) { + int condY = renderConditions(sw, builder.getLastBuildY(), builder.getNextLabelId()); + sw.maxScrollY = Math.max(condY - swH, 0); + } + + // Restore scroll position + if (activeTab < tabScrollY.length) { + float restored = Math.min(tabScrollY[activeTab], sw.maxScrollY); + sw.nextScrollY = restored; + sw.scrollY = restored; } } - // ═══════════════════════════════════════════════════════════════════════════ - // GENERAL TAB - // ═══════════════════════════════════════════════════════════════════════════ + private List getVisibleFieldsForTab(int tabIndex) { + List result = new ArrayList<>(); - private void initGeneralTab(int startY) { - int y = startY; - int col1LabelX = guiLeft + 8; - int col1FieldX = guiLeft + 70; - int col2LabelX = guiLeft + 180; - int col2FieldX = guiLeft + 248; - - // Row 1: Type (read-only) + Name - addLabel(new GuiNpcLabel(1, "gui.type", col1LabelX, y + 5)); - addLabel(new GuiNpcLabel(2, ability.getTypeId(), col1FieldX, y + 5)); - - addLabel(new GuiNpcLabel(3, "gui.name", col2LabelX, y + 5)); - GuiNpcTextField nameField = new GuiNpcTextField(1, this, fontRendererObj, col2FieldX, y, 100, 20, name); - addTextField(nameField); - - y += 24; - - // Row 2: Weight + Lock Movement - addLabel(new GuiNpcLabel(4, "ability.weight", col1LabelX, y + 5)); - GuiNpcTextField weightField = new GuiNpcTextField(3, this, fontRendererObj, col1FieldX, y, 40, 20, "" + weight); - weightField.setIntegersOnly(); - weightField.setMinMaxDefault(1, 1000, 10); - addTextField(weightField); - - addLabel(new GuiNpcLabel(5, "ability.lockMove", col2LabelX, y + 5)); - GuiNpcButton lockMoveBtn = new GuiNpcButton(16, col2FieldX, y, 60, 20, LockMovementType.getDisplayKeys(), lockMovement.ordinal()); - lockMoveBtn.setHoverText("ability.hover.lockMove"); - addButton(lockMoveBtn); - - y += 24; - - // Row 3: Interruptible + Dazed Ticks (only if interruptible) - addLabel(new GuiNpcLabel(6, "ability.interruptible", col1LabelX, y + 5)); - GuiNpcButton interruptBtn = new GuiNpcButton(14, guiLeft + 85, y, 40, 20, new String[]{"gui.no", "gui.yes"}, interruptible ? 1 : 0); - interruptBtn.setHoverText("ability.hover.interruptible"); - addButton(interruptBtn); - - // Only show dazed ticks if interruptible is enabled - if (interruptible) { - addLabel(new GuiNpcLabel(12, "ability.dazed", col2LabelX, y + 5)); - GuiNpcTextField dazedField = new GuiNpcTextField(13, this, fontRendererObj, col2FieldX, y, 40, 20, "" + dazedTicks); - dazedField.setIntegersOnly(); - dazedField.setMinMaxDefault(0, 1000, 80); - addTextField(dazedField); - } - - y += 28; - - // Separator - Timing section header - addLabel(new GuiNpcLabel(7, "ability.timing", col1LabelX, y)); - y += 14; - - // Check if windup animation is selected (either by name or ID) - boolean hasWindupAnimation = windUpAnimationId >= 0 || (windUpAnimationName != null && !windUpAnimationName.isEmpty()); - - // Row 4: Windup Ticks + Cooldown Ticks - addLabel(new GuiNpcLabel(10, "ability.windup", col1LabelX, y + 5)); - - // Only show windup textbox if sync is off or no animation selected - if (!syncWindupWithAnimation || !hasWindupAnimation) { - GuiNpcTextField windupField = new GuiNpcTextField(11, this, fontRendererObj, col1FieldX, y, 40, 20, "" + windUpTicks); - windupField.setIntegersOnly(); - windupField.setMinMaxDefault(0, 1000, 20); - addTextField(windupField); + String tabName; + if (tabIndex >= 4) { + int customIndex = tabIndex - 4; + if (customIndex >= 0 && customIndex < customTabNames.size()) { + tabName = customTabNames.get(customIndex); + } else { + return result; + } } else { - // Show calculated value as label when synced - addLabel(new GuiNpcLabel(11, "" + windUpTicks, col1FieldX + 5, y + 5)); + switch (tabIndex) { + case TAB_GENERAL: tabName = TAB_NAME_GENERAL; break; + case TAB_TYPE: tabName = TAB_NAME_TYPE; break; + case TAB_TARGET: tabName = TAB_NAME_TARGET; break; + case TAB_EFFECTS: tabName = TAB_NAME_EFFECTS; break; + default: tabName = TAB_NAME_TYPE; break; + } } - // Sync toggle button - only show if windup animation is selected - if (hasWindupAnimation) { - String syncLabel = syncWindupWithAnimation ? "ability.syncOn" : "ability.syncOff"; - GuiNpcButton syncBtn = new GuiNpcButton(17, guiLeft + 115, y, 50, 20, syncLabel); - syncBtn.setHoverText("ability.hover.sync"); - addButton(syncBtn); + for (FieldDef def : fieldDefs) { + if (tabName.equals(def.getTab()) && def.isVisible()) { + result.add(def); + } } - addLabel(new GuiNpcLabel(13, "ability.cooldown", col2LabelX, y + 5)); - GuiNpcTextField cooldownField = new GuiNpcTextField(10, this, fontRendererObj, col2FieldX, y, 40, 20, "" + cooldownTicks); - cooldownField.setIntegersOnly(); - cooldownField.setMinMaxDefault(0, 10000, 0); - addTextField(cooldownField); + return result; } // ═══════════════════════════════════════════════════════════════════════════ - // TYPE TAB - Override in subclasses for type-specific settings + // CONDITIONS (Target tab) // ═══════════════════════════════════════════════════════════════════════════ - /** - * Override this method to render type-specific settings in the Type tab. - * Use the helper methods createFloatField(), createIntField(), etc. - * Button/TextField IDs should start at 100. - * - * @param startY The Y position to start rendering from - */ - protected void initTypeTab(int startY) { - // Default: show message that no type settings are available - addLabel(new GuiNpcLabel(100, "ability.noTypeSettings", guiLeft + 8, startY + 5)); - } + private int renderConditions(GuiScrollWindow sw, int y, int labelCounter) { + y += 3; + sw.addLabel(new GuiNpcLabel(labelCounter, "ability.conditions", L_LABEL_X, y + 2, 0xFFFF55)); + y += 15; - /** - * Override this method to handle button clicks for type-specific buttons. - * Button IDs 100+ are reserved for type-specific use. - */ - protected void handleTypeButton(int id, GuiNpcButton button) { - // Default: no-op - } - - /** - * Override this method to handle text field changes for type-specific fields. - * Field IDs 100+ are reserved for type-specific use. - */ - protected void handleTypeTextField(int id, GuiNpcTextField field) { - // Default: no-op - } - - // ═══════════════════════════════════════════════════════════════════════════ - // VISUAL TAB - Override in subclasses for visual settings (colors, etc.) - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Override to return true if this ability has visual settings (colors, glow, etc.). - * When true, a Visual tab will be shown in the GUI. - */ - protected boolean hasVisualSettings() { - return false; - } - - /** - * Override this method to render visual settings in the Visual tab. - * Use button/text field IDs starting at 200 for visual settings. - * - * @param startY The Y position to start rendering from - */ - protected void initVisualTab(int startY) { - // Default: show message that no visual settings are available - addLabel(new GuiNpcLabel(200, "ability.noVisualSettings", guiLeft + 8, startY + 5)); - } - - /** - * Override this method to handle button clicks for visual-specific buttons. - * Button IDs 200+ are reserved for visual-specific use. - */ - protected void handleVisualButton(int id, GuiNpcButton button) { - // Default: no-op - } - - /** - * Override this method to handle text field changes for visual-specific fields. - * Field IDs 200+ are reserved for visual-specific use. - */ - protected void handleVisualTextField(int id, GuiNpcTextField field) { - // Default: no-op - } - - // ═══════════════════════════════════════════════════════════════════════════ - // TARGET TAB - // ═══════════════════════════════════════════════════════════════════════════ - - private void initTargetTab(int startY) { - int y = startY; - int col1LabelX = guiLeft + 8; - int col1FieldX = guiLeft + 70; - int col2LabelX = guiLeft + 180; - int col2FieldX = guiLeft + 248; - - // Row 1: Min Range + Max Range - addLabel(new GuiNpcLabel(20, "ability.minRange", col1LabelX, y + 5)); - GuiNpcTextField minRangeField = new GuiNpcTextField(5, this, fontRendererObj, col1FieldX, y, 40, 20, "" + (int) minRange); - minRangeField.setIntegersOnly(); - minRangeField.setMinMaxDefault(0, 100, 0); - addTextField(minRangeField); - - addLabel(new GuiNpcLabel(21, "ability.maxRange", col2LabelX, y + 5)); - GuiNpcTextField maxRangeField = new GuiNpcTextField(6, this, fontRendererObj, col2FieldX, y, 40, 20, "" + (int) maxRange); - maxRangeField.setIntegersOnly(); - maxRangeField.setMinMaxDefault(1, 100, 20); - addTextField(maxRangeField); - - y += 24; - - // Row 2: Targeting Mode (if not locked) - addLabel(new GuiNpcLabel(22, "ability.targeting", col1LabelX, y + 5)); - if (!targetingModeLocked) { - String[] targetingModes = getAvailableTargetingModes(); - int selectedIndex = getTargetingModeIndex(targetingMode); - GuiNpcButton targetBtn = new GuiNpcButton(4, col1FieldX, y, 90, 20, targetingModes, selectedIndex); - targetBtn.setHoverText("ability.hover.targeting"); - addButton(targetBtn); - } else { - String modeName = "ability.target." + targetingMode.name().toLowerCase(); - addLabel(new GuiNpcLabel(23, modeName, col1FieldX, y + 5)); - } - - y += 28; - - // ───────────────────────────────────────────────────────────────────── - // CONDITIONS SECTION (up to 3) - // ───────────────────────────────────────────────────────────────────── - addLabel(new GuiNpcLabel(24, "ability.conditions", col1LabelX, y)); - y += 14; - - // Display existing conditions (similar to Marks pattern) for (int i = 0; i < conditions.size() && i < 3; i++) { Condition cond = conditions.get(i); String condName = getConditionDisplayName(cond); - - // Condition type button - addButton(new GuiNpcButton(50 + i * 10, col1LabelX, y, 140, 20, condName)); - - // Edit button - addButton(new GuiNpcButton(51 + i * 10, col1LabelX + 145, y, 40, 20, "gui.edit")); - - // Delete button - addButton(new GuiNpcButton(52 + i * 10, col1LabelX + 190, y, 20, 20, "X")); - + sw.addButton(new GuiNpcButton(50 + i * 10, L_LABEL_X, y, 140, 20, condName)); + sw.addButton(new GuiNpcButton(51 + i * 10, L_LABEL_X + 145, y, 40, 20, "gui.edit")); + sw.addButton(new GuiNpcButton(52 + i * 10, L_LABEL_X + 190, y, 20, 20, "X")); y += 22; } - // Add button (if less than 3 conditions) if (conditions.size() < 3) { - addButton(new GuiNpcButton(80, col1LabelX, y, 50, 20, "gui.add")); + sw.addButton(new GuiNpcButton(80, L_LABEL_X, y, 50, 20, "gui.add")); + y += ROW_H; } + + return y; } private String getConditionDisplayName(Condition cond) { @@ -469,155 +243,18 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi case "target_hp_below": return StatCollector.translateToLocal("condition.target_hp_below") + " " + (int) (getConditionThreshold(cond) * 100) + "%"; case "hit_count": - Condition.ConditionHitCount hitCount = (Condition.ConditionHitCount) cond; - return StatCollector.translateToLocal("condition.hit_count") + ": " + hitCount.getRequiredHits() + "/" + hitCount.getWithinTicks() + "t"; + Condition.ConditionHitCount hc = (Condition.ConditionHitCount) cond; + return StatCollector.translateToLocal("condition.hit_count") + ": " + hc.getRequiredHits() + "/" + hc.getWithinTicks() + "t"; default: return typeId; } } private float getConditionThreshold(Condition cond) { - // Read threshold from NBT since inner classes don't expose it NBTTagCompound nbt = cond.writeNBT(); return nbt.hasKey("threshold") ? nbt.getFloat("threshold") : 0.5f; } - private String[] getAvailableTargetingModes() { - TargetingMode[] modes = ability.getAllowedTargetingModes(); - if (modes == null) { - modes = TargetingMode.values(); - } - String[] result = new String[modes.length]; - for (int i = 0; i < modes.length; i++) { - result[i] = "ability.target." + modes[i].name().toLowerCase(); - } - return result; - } - - private int getTargetingModeIndex(TargetingMode mode) { - TargetingMode[] modes = ability.getAllowedTargetingModes(); - if (modes == null) { - return mode.ordinal(); - } - for (int i = 0; i < modes.length; i++) { - if (modes[i] == mode) return i; - } - return 0; - } - - // ═══════════════════════════════════════════════════════════════════════════ - // EFFECTS TAB - // ═══════════════════════════════════════════════════════════════════════════ - - private void initEffectsTab(int startY) { - int y = startY; - int col1LabelX = guiLeft + 8; - int col1FieldX = guiLeft + 85; - int col1ClearX = guiLeft + 160; - int col2LabelX = guiLeft + 185; - int col2FieldX = guiLeft + 255; - - // ───────────────────────────────────────────────────────────────────── - // SOUNDS SECTION - // ───────────────────────────────────────────────────────────────────── - addLabel(new GuiNpcLabel(30, "advanced.sounds", col1LabelX, y)); - y += 14; - - // Wind Up Sound - addLabel(new GuiNpcLabel(31, "ability.windUpSound", col1LabelX, y + 5)); - String windUpSoundDisplay = windUpSound != null && !windUpSound.isEmpty() ? truncateString(windUpSound, 10) : StatCollector.translateToLocal("gui.none"); - addButton(new GuiNpcButton(30, col1FieldX, y, 70, 20, windUpSoundDisplay)); - addButton(new GuiNpcButton(35, col1ClearX, y, 20, 20, "X")); - - // Active Sound - addLabel(new GuiNpcLabel(32, "ability.activeSound", col2LabelX, y + 5)); - String activeSoundDisplay = activeSound != null && !activeSound.isEmpty() ? truncateString(activeSound, 10) : StatCollector.translateToLocal("gui.none"); - addButton(new GuiNpcButton(31, col2FieldX, y, 70, 20, activeSoundDisplay)); - addButton(new GuiNpcButton(36, col2FieldX + 75, y, 20, 20, "X")); - - y += 26; - - // ───────────────────────────────────────────────────────────────────── - // ANIMATIONS SECTION - // ───────────────────────────────────────────────────────────────────── - addLabel(new GuiNpcLabel(33, "menu.animations", col1LabelX, y)); - y += 14; - - // Wind Up Animation - addLabel(new GuiNpcLabel(34, "ability.windUpAnim", col1LabelX, y + 5)); - String windUpAnimName = getAnimationName(windUpAnimationId, true); - addButton(new GuiNpcButton(32, col1FieldX, y, 70, 20, windUpAnimName)); - addButton(new GuiNpcButton(37, col1ClearX, y, 20, 20, "X")); - - // Active Animation - addLabel(new GuiNpcLabel(35, "ability.activeAnim", col2LabelX, y + 5)); - String activeAnimName = getAnimationName(activeAnimationId, false); - addButton(new GuiNpcButton(33, col2FieldX, y, 70, 20, activeAnimName)); - addButton(new GuiNpcButton(38, col2FieldX + 75, y, 20, 20, "X")); - - y += 26; - - // ───────────────────────────────────────────────────────────────────── - // TELEGRAPH SECTION (only if supported) - // ───────────────────────────────────────────────────────────────────── - if (supportsTelegraph) { - addLabel(new GuiNpcLabel(40, "ability.telegraph", col1LabelX, y)); - y += 14; - - // Show Telegraph - addLabel(new GuiNpcLabel(41, "ability.showTelegraph", col1LabelX, y + 5)); - GuiNpcButton telegraphBtn = new GuiNpcButton(20, guiLeft + 95, y, 40, 20, new String[]{"gui.no", "gui.yes"}, showTelegraph ? 1 : 0); - telegraphBtn.setHoverText("ability.hover.showTelegraph"); - addButton(telegraphBtn); - - // Telegraph Type (separate column) - String typeKey = ability.getTelegraphType().name().toLowerCase(); - addLabel(new GuiNpcLabel(42, "ability.telegraphType", guiLeft + 200, y + 5)); - String telegraphLangKey = typeKey.equals("none") ? "gui.none" : "telegraph." + typeKey; - addLabel(new GuiNpcLabel(43, telegraphLangKey, guiLeft + 280, y + 5)); - - y += 24; - - // Colors - only show when telegraph is enabled - if (showTelegraph) { - addLabel(new GuiNpcLabel(44, "ability.windUpColor", col1LabelX, y + 5)); - String windUpHex = String.format("%06X", windUpColor & 0xFFFFFF); - GuiNpcButton windUpColorBtn = new GuiNpcButton(22, guiLeft + 95, y, 55, 20, windUpHex); - windUpColorBtn.setTextColor(windUpColor & 0xFFFFFF); - addButton(windUpColorBtn); - - addLabel(new GuiNpcLabel(45, "ability.activeColor", guiLeft + 200, y + 5)); - String activeHex = String.format("%06X", activeColor & 0xFFFFFF); - GuiNpcButton activeColorBtn = new GuiNpcButton(24, guiLeft + 280, y, 55, 20, activeHex); - activeColorBtn.setTextColor(activeColor & 0xFFFFFF); - addButton(activeColorBtn); - } - } - } - - private String truncateString(String str, int maxLen) { - if (str == null) return ""; - if (str.length() <= maxLen) return str; - int lastSlash = str.lastIndexOf('/'); - if (lastSlash >= 0 && str.length() - lastSlash <= maxLen) { - return "..." + str.substring(lastSlash); - } - return "..." + str.substring(str.length() - maxLen + 3); - } - - private String getAnimationName(int animId, boolean isWindUp) { - String animName = isWindUp ? windUpAnimationName : activeAnimationName; - // Check if we have a built-in animation (by name) - if (animName != null && !animName.isEmpty()) { - return truncateString(animName, 8); - } - // Check if we have a user animation (by ID) - if (animId >= 0) { - return "ID: " + animId; - } - return StatCollector.translateToLocal("gui.none"); - } - // ═══════════════════════════════════════════════════════════════════════════ // BUTTON EVENTS // ═══════════════════════════════════════════════════════════════════════════ @@ -626,154 +263,58 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi public void buttonEvent(GuiButton guibutton) { int id = guibutton.id; - // Tab switching - if (id == 90) { - activeTab = TAB_GENERAL; - initGui(); - return; - } - if (id == 91 && hasTypeSettings) { - activeTab = TAB_TYPE; - initGui(); - return; - } - if (id == 92) { - activeTab = TAB_TARGET; - initGui(); - return; - } - if (id == 93) { - activeTab = TAB_EFFECTS; - initGui(); - return; - } - if (id == 94 && hasVisualSettings) { - activeTab = TAB_VISUAL; + // Tab switching — fixed tabs + if (id == 90) { activeTab = TAB_GENERAL; initGui(); return; } + if (id == 91) { activeTab = TAB_TYPE; initGui(); return; } + if (id == 92) { activeTab = TAB_TARGET; initGui(); return; } + if (id == 93) { activeTab = TAB_EFFECTS; initGui(); return; } + // Custom tabs (94+) + if (id >= 94 && id < 94 + customTabNames.size()) { + activeTab = 4 + (id - 94); initGui(); return; } + if (id == -1000) { close(); return; } - // Enabled button (bottom left) - if (id == 2) { - enabled = ((GuiNpcButton) guibutton).getValue() == 1; - initGui(); - } + // Condition buttons (50-80) + if (handleConditionButton(id)) return; - // General tab buttons - else if (id == 14) { - interruptible = ((GuiNpcButton) guibutton).getValue() == 1; - initGui(); // Refresh to show/hide dazed ticks field - } else if (id == 16) { - lockMovement = LockMovementType.fromOrdinal(((GuiNpcButton) guibutton).getValue()); - } else if (id == 17) { - // Toggle sync on/off - syncWindupWithAnimation = !syncWindupWithAnimation; - if (syncWindupWithAnimation) { - // Calculate windup ticks from animation when turning sync on - calculateWindupFromAnimation(); + // Declarative field handling (effects list, booleans, enums, sub-guis, clear buttons) + if (builder.handleButtonEvent(id, guibutton)) { + // SUB_GUI fields are opened directly by the builder via setSubGuiWithResult(). + // Only rebuild if no sub-gui was opened (e.g. boolean toggle, enum change). + if (!hasSubGui()) { + initGui(); } - initGui(); - } - - // Target tab - Targeting mode - else if (id == 4) { - TargetingMode[] modes = ability.getAllowedTargetingModes(); - int idx = ((GuiNpcButton) guibutton).getValue(); - if (modes != null && idx < modes.length) { - targetingMode = modes[idx]; - } else { - targetingMode = TargetingMode.values()[idx]; - } - } - - // Close button (X in top menu) - use -1000 to avoid any ID conflicts - else if (id == -1000) { - close(); return; } + } - // Target tab - Condition buttons (50-79) - else if (id >= 50 && id < 80) { + private boolean handleConditionButton(int id) { + if (id >= 50 && id < 80) { int condIndex = (id - 50) / 10; int action = (id - 50) % 10; - if (action == 0 || action == 1) { - // Click on condition name or Edit button - open edit subgui if (condIndex < conditions.size()) { editingConditionIndex = condIndex; setSubGui(new SubGuiConditionEdit(conditions.get(condIndex))); } } else if (action == 2) { - // Delete button if (condIndex < conditions.size()) { conditions.remove(condIndex); initGui(); } } + return true; } - // Add condition button - else if (id == 80) { + if (id == 80) { if (conditions.size() < 3) { editingConditionIndex = conditions.size(); setSubGui(new SubGuiConditionEdit(null)); } + return true; } - - // Effects tab - Telegraph - else if (id == 20) { - showTelegraph = ((GuiNpcButton) guibutton).getValue() == 1; - initGui(); - } else if (id == 22) { - editingColorId = 22; - setSubGui(new SubGuiColorSelector(windUpColor)); - } else if (id == 24) { - editingColorId = 24; - setSubGui(new SubGuiColorSelector(activeColor)); - } - - // Effects tab - Sound buttons - else if (id == 30) { - editingSoundId = 30; - setSubGui(new GuiSoundSelection(windUpSound)); - } else if (id == 31) { - editingSoundId = 31; - setSubGui(new GuiSoundSelection(activeSound)); - } - // Sound clear buttons - else if (id == 35) { - windUpSound = ""; - initGui(); - } else if (id == 36) { - activeSound = ""; - initGui(); - } - // Animation buttons - else if (id == 32) { - editingAnimationId = 32; - setSubGui(new GuiAnimationSelection(windUpAnimationId, windUpAnimationName)); - } else if (id == 33) { - editingAnimationId = 33; - setSubGui(new GuiAnimationSelection(activeAnimationId, activeAnimationName)); - } - // Animation clear buttons - else if (id == 37) { - windUpAnimationId = -1; - windUpAnimationName = ""; - initGui(); - } else if (id == 38) { - activeAnimationId = -1; - activeAnimationName = ""; - initGui(); - } - - // Visual-specific buttons (200+) - delegate to subclass - else if (id >= 200) { - handleVisualButton(id, (GuiNpcButton) guibutton); - } - // Type-specific buttons (100-199) - delegate to subclass - else if (id >= 100) { - handleTypeButton(id, (GuiNpcButton) guibutton); - } + return false; } // ═══════════════════════════════════════════════════════════════════════════ @@ -782,95 +323,24 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi @Override public void unFocused(GuiNpcTextField textField) { - int id = textField.id; - - // General tab - if (id == 1) { - name = textField.getText(); - } else if (id == 3) { - weight = textField.getInteger(); - } - - // Target tab - else if (id == 5) { - minRange = textField.getInteger(); - } else if (id == 6) { - maxRange = textField.getInteger(); - } - - // Timing (General tab) - else if (id == 10) { - cooldownTicks = textField.getInteger(); - } else if (id == 11) { - windUpTicks = textField.getInteger(); - } else if (id == 13) { - dazedTicks = textField.getInteger(); - } - - // Visual-specific fields (200+) - delegate to subclass - else if (id >= 200) { - handleVisualTextField(id, textField); - } - // Type-specific fields (100-199) - delegate to subclass - else if (id >= 100) { - handleTypeTextField(id, textField); + if (textField.id < DECLARATIVE_ID_START) return; + if (builder.handleTextFieldEvent(textField.id, textField)) { + initGui(); } } // ═══════════════════════════════════════════════════════════════════════════ - // SUBGUI CLOSED HANDLER + // SUB GUI CLOSED // ═══════════════════════════════════════════════════════════════════════════ @Override public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiColorSelector) { - SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui; - int rgb = colorSelector.color & 0x00FFFFFF; - if (editingColorId == 22) { - windUpColor = 0x80000000 | rgb; - } else if (editingColorId == 24) { - activeColor = 0xC0000000 | rgb; - } - editingColorId = 0; + if (builder.handleSubGuiClosed(subgui)) { initGui(); - } else if (subgui instanceof GuiSoundSelection) { - GuiSoundSelection soundSelector = (GuiSoundSelection) subgui; - if (soundSelector.selectedResource != null) { - String sound = soundSelector.selectedResource.toString(); - if (editingSoundId == 30) { - windUpSound = sound; - } else if (editingSoundId == 31) { - activeSound = sound; - } - } - editingSoundId = 0; - initGui(); - } else if (subgui instanceof GuiAnimationSelection) { - GuiAnimationSelection animSelector = (GuiAnimationSelection) subgui; - if (editingAnimationId == 32) { - if (animSelector.isBuiltInSelected()) { - // Built-in animation selected - use name, clear ID - windUpAnimationName = animSelector.selectedBuiltInName; - windUpAnimationId = -1; - } else { - // User animation selected - use ID, clear name - windUpAnimationId = animSelector.selectedAnimationId; - windUpAnimationName = ""; - } - } else if (editingAnimationId == 33) { - if (animSelector.isBuiltInSelected()) { - // Built-in animation selected - use name, clear ID - activeAnimationName = animSelector.selectedBuiltInName; - activeAnimationId = -1; - } else { - // User animation selected - use ID, clear name - activeAnimationId = animSelector.selectedAnimationId; - activeAnimationName = ""; - } - } - editingAnimationId = 0; - initGui(); - } else if (subgui instanceof SubGuiConditionEdit) { + return; + } + + if (subgui instanceof SubGuiConditionEdit) { SubGuiConditionEdit condEdit = (SubGuiConditionEdit) subgui; Condition result = condEdit.getResult(); if (result != null && editingConditionIndex >= 0) { @@ -886,178 +356,34 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi } // ═══════════════════════════════════════════════════════════════════════════ - // CLOSE - Save before closing + // CLOSE / APPLY // ═══════════════════════════════════════════════════════════════════════════ @Override public void close() { - // Apply all cached values to the ability before closing + GuiNpcTextField.unfocus(); applyToAbility(); - - // Notify callback that ability was saved callback.onAbilitySaved(ability); - - // Close the GUI super.close(); } - // ═══════════════════════════════════════════════════════════════════════════ - // APPLY TO ABILITY - // ═══════════════════════════════════════════════════════════════════════════ - protected void applyToAbility() { - // General - ability.setName(name); - ability.setEnabled(enabled); - ability.setWeight(weight); - ability.setLockMovement(lockMovement); - ability.setInterruptible(interruptible); - - // If sync is enabled and we have a windup animation, recalculate before saving - boolean hasWindupAnimation = windUpAnimationId >= 0 || (windUpAnimationName != null && !windUpAnimationName.isEmpty()); - if (syncWindupWithAnimation && hasWindupAnimation) { - calculateWindupFromAnimation(); - } - - // Timing - ability.setCooldownTicks(cooldownTicks); - ability.setWindUpTicks(windUpTicks); - ability.setDazedTicks(dazedTicks); - - // Target - ability.setMinRange(minRange); - ability.setMaxRange(maxRange); - ability.setTargetingMode(targetingMode); - - // Conditions ability.getConditions().clear(); - for (Condition c : conditions) { - ability.addCondition(c); - } - - // Effects - ability.setWindUpSound(windUpSound); - ability.setActiveSound(activeSound); - ability.setWindUpAnimationId(windUpAnimationId); - ability.setActiveAnimationId(activeAnimationId); - ability.setWindUpAnimationName(windUpAnimationName != null ? windUpAnimationName : ""); - ability.setActiveAnimationName(activeAnimationName != null ? activeAnimationName : ""); - - // Telegraph - ability.setShowTelegraph(showTelegraph); - ability.setWindUpColor(windUpColor); - ability.setActiveColor(activeColor); - - // Type-specific values are applied directly in handleTypeTextField and handleTypeButton + for (Condition c : conditions) ability.addCondition(c); } - /** - * Called when an ability is loaded from saved presets. - */ public void loadAbility(Ability loadedAbility) { if (loadedAbility == null) return; - - // Copy all values from loaded ability to current ability NBTTagCompound nbt = loadedAbility.writeNBT(); - // Keep the current typeId since we can't change types mid-edit nbt.setString("typeId", ability.getTypeId()); ability.readNBT(nbt); - // Update cached values - this.name = ability.getName() != null ? ability.getName() : ""; - this.enabled = ability.isEnabled(); - this.weight = ability.getWeight(); - this.lockMovement = ability.getLockMovement(); - this.interruptible = ability.isInterruptible(); - - this.cooldownTicks = ability.getCooldownTicks(); - this.windUpTicks = ability.getWindUpTicks(); - this.dazedTicks = ability.getDazedTicks(); - - this.minRange = ability.getMinRange(); - this.maxRange = ability.getMaxRange(); - this.targetingMode = ability.getTargetingMode(); this.conditions = new ArrayList<>(ability.getConditions()); - - this.showTelegraph = ability.isShowTelegraph(); - this.windUpColor = ability.getWindUpColor(); - this.activeColor = ability.getActiveColor(); - + this.fieldDefs = ability.getAllDefinitions(); + discoverCustomTabs(); initGui(); } - // ═══════════════════════════════════════════════════════════════════════════ - // SYNC ANIMATION - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Calculates windup ticks from the selected windup animation's total duration. - */ - private void calculateWindupFromAnimation() { - if (AnimationController.Instance == null) { - return; - } - - Animation animation = null; - // Check for built-in animation (by name) first - if (windUpAnimationName != null && !windUpAnimationName.isEmpty()) { - animation = (Animation) AnimationController.Instance.get(windUpAnimationName); - } - // Fall back to user animation (by ID) - else if (windUpAnimationId >= 0) { - animation = (Animation) AnimationController.Instance.get(windUpAnimationId); - } - - if (animation == null || animation.frames.isEmpty()) { - return; - } - - // Calculate total duration by summing all frame durations - int totalDuration = 0; - for (Frame frame : animation.frames) { - totalDuration += frame.getDuration(); - } - - // Update the cached value and refresh GUI - windUpTicks = totalDuration; - initGui(); - } - - // ═══════════════════════════════════════════════════════════════════════════ - // HELPER METHODS FOR SUBCLASSES - // ═══════════════════════════════════════════════════════════════════════════ - - /** - * Creates a float text field for type-specific settings. - */ - protected GuiNpcTextField createFloatField(int id, int x, int y, int width, float value) { - GuiNpcTextField field = new GuiNpcTextField(id, this, fontRendererObj, x, y, width, 20, String.format("%.1f", value)); - return field; - } - - /** - * Creates an integer text field for type-specific settings. - */ - protected GuiNpcTextField createIntField(int id, int x, int y, int width, int value) { - GuiNpcTextField field = new GuiNpcTextField(id, this, fontRendererObj, x, y, width, 20, "" + value); - field.setIntegersOnly(); - return field; - } - - /** - * Parses a float from a text field with a fallback default value. - */ - protected float parseFloat(GuiNpcTextField field, float defaultValue) { - try { - return Float.parseFloat(field.getText()); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - /** - * Gets the ability being edited. - */ protected Ability getAbility() { return ability; } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java index 68a74cb8b..103d446fc 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityLoad.java @@ -10,6 +10,7 @@ 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.GuiNpcTextField; import noppes.npcs.client.gui.util.ICustomScrollListener; import noppes.npcs.client.gui.util.IGuiData; import noppes.npcs.client.gui.util.IScrollData; @@ -39,6 +40,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL private HashMap rawData = new HashMap<>(); private GuiCustomScroll scroll; + private String search = ""; private boolean waitingForLoad = false; private int pendingLoadMode = -1; @@ -48,7 +50,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL setBackground("menubg.png"); xSize = 220; - ySize = 180; + ySize = 216; PacketClient.sendClient(new CustomAbilitiesGetPacket()); } @@ -59,7 +61,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL setBackground("menubg.png"); xSize = 220; - ySize = 180; + ySize = 216; PacketClient.sendClient(new CustomAbilitiesGetPacket()); } @@ -75,7 +77,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL if (scroll == null) { scroll = new GuiCustomScroll(this, 0); - scroll.setSize(200, 110); + scroll.setSize(200, 140); } scroll.guiLeft = guiLeft + 10; scroll.guiTop = y; @@ -85,7 +87,12 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL } addScroll(scroll); - y += 115; + y += 143; + + // Search bar + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 10, y, 200, 20, search)); + + y += 24; addButton(new GuiNpcButton(0, guiLeft + 10, y, 95, 20, "gui.load")); addButton(new GuiNpcButton(2, guiLeft + 115, y, 95, 20, "gui.cancel")); @@ -94,7 +101,16 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL } private List getFilteredList() { - return new ArrayList<>(displayToUuid.keySet()); + if (search.isEmpty()) { + return new ArrayList<>(displayToUuid.keySet()); + } + List list = new ArrayList<>(); + for (String name : displayToUuid.keySet()) { + if (name.toLowerCase().contains(search.toLowerCase())) { + list.add(name); + } + } + return list; } @Override @@ -116,6 +132,19 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL } } + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(10) != null && getTextField(10).isFocused()) { + String newSearch = getTextField(10).getText(); + if (!search.equals(newSearch)) { + search = newSearch; + scroll.resetScroll(); + scroll.setList(getFilteredList()); + } + } + } + @Override public void subGuiClosed(SubGuiInterface subgui) { if (subgui instanceof SubGuiAbilityLoadMode) { diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java index 9407d20c5..b8a4e0e66 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilitySaveConfirm.java @@ -7,24 +7,29 @@ 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.ISubGuiListener; import noppes.npcs.client.gui.util.SubGuiInterface; +import java.util.Set; + /** * Confirmation dialog for saving an ability preset. * Uses packet-based communication for proper client-server architecture. */ -public class SubGuiAbilitySaveConfirm extends SubGuiInterface { +public class SubGuiAbilitySaveConfirm extends SubGuiInterface implements ISubGuiListener { private final Ability ability; private final IAbilityConfigCallback callback; + private final Set existingNames; public SubGuiAbilitySaveConfirm(Ability ability) { - this(ability, null); + this(ability, null, null); } - public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback) { + public SubGuiAbilitySaveConfirm(Ability ability, IAbilityConfigCallback callback, Set existingNames) { this.ability = ability; this.callback = callback; + this.existingNames = existingNames; setBackground("menubg.png"); xSize = 200; @@ -52,14 +57,32 @@ public class SubGuiAbilitySaveConfirm extends SubGuiInterface { int id = guibutton.id; if (id == 0) { - // Save the ability via packet - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); - if (callback != null) { - callback.onAbilitySaved(ability); + if (existingNames != null && existingNames.contains(ability.getName())) { + setSubGui(new SubGuiDuplicateNameConfirm()); + return; } - close(); + doSave(); } else if (id == 1) { close(); } } + + private void doSave() { + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + if (callback != null) { + callback.onAbilitySaved(ability); + } + close(); + } + + @Override + public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiDuplicateNameConfirm) { + if (((SubGuiDuplicateNameConfirm) subgui).isConfirmed()) { + doSave(); + } else { + close(); + } + } + } } diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java new file mode 100644 index 000000000..5d810862f --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityTypeSelect.java @@ -0,0 +1,125 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.AbilityController; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.resources.I18n; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.ITextfieldListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * SubGui for selecting an ability type when creating a new ability. + */ +public class SubGuiAbilityTypeSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener { + + private GuiCustomScroll scroll; + private final HashMap displayNameToTypeId = new HashMap<>(); + private final HashMap allDisplayNameToTypeId = new HashMap<>(); + private String selectedTypeId = null; + private String search = ""; + + public SubGuiAbilityTypeSelect() { + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + addTextField(new GuiNpcTextField(10, this, fontRendererObj, guiLeft + 5, guiTop + 5, 190, 18, search)); + + if (scroll == null) { + scroll = new GuiCustomScroll(this, 0); + scroll.setSize(190, 145); + } + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = guiTop + 26; + addScroll(scroll); + + buildAllTypes(); + scroll.setList(getFilteredTypeList()); + + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.add")); + getButton(0).setEnabled(scroll.hasSelected()); + addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); + } + + private void buildAllTypes() { + allDisplayNameToTypeId.clear(); + String[] types = AbilityController.Instance.getTypes(); + for (String typeId : types) { + String displayName = I18n.format(typeId); + allDisplayNameToTypeId.put(displayName, typeId); + } + } + + private List getFilteredTypeList() { + List list = new ArrayList<>(); + displayNameToTypeId.clear(); + for (Map.Entry entry : allDisplayNameToTypeId.entrySet()) { + String displayName = entry.getKey(); + if (search.isEmpty() || displayName.toLowerCase().contains(search) || entry.getValue().toLowerCase().contains(search)) { + list.add(displayName); + displayNameToTypeId.put(displayName, entry.getValue()); + } + } + return list; + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0 && scroll.hasSelected()) { + String displayName = scroll.getSelected(); + selectedTypeId = displayNameToTypeId.get(displayName); + close(); + } else if (guibutton.id == 1) { + selectedTypeId = null; + close(); + } + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0) { + getButton(0).setEnabled(scroll.hasSelected()); + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll guiCustomScroll) { + if (guiCustomScroll.id == 0 && selection != null) { + selectedTypeId = displayNameToTypeId.get(selection); + close(); + } + } + + @Override + public void keyTyped(char c, int i) { + super.keyTyped(c, i); + if (getTextField(10) != null && getTextField(10).isFocused()) { + if (!search.equals(getTextField(10).getText())) { + search = getTextField(10).getText().toLowerCase(); + scroll.setList(getFilteredTypeList()); + scroll.resetScroll(); + } + } + } + + @Override + public void unFocused(GuiNpcTextField textField) { + } + + public String getSelectedTypeId() { + return selectedTypeId; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java new file mode 100644 index 000000000..1c65d0dc6 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityVariantSelect.java @@ -0,0 +1,154 @@ +package noppes.npcs.client.gui.advanced; + +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import net.minecraft.client.gui.GuiButton; +import noppes.npcs.client.gui.util.GuiCustomScroll; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.ICustomScrollListener; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.ArrayList; +import java.util.List; + +/** + * SubGui for selecting a variant/template when creating a new ability. + * Uses a scroll list with group headers for external addon variants. + */ +public class SubGuiAbilityVariantSelect extends SubGuiInterface implements ICustomScrollListener { + + private final List variants; + private int selectedIndex = -1; + + // Maps each scroll list index to a variant list index (-1 for non-selectable entries) + private final List scrollToVariantIndex = new ArrayList<>(); + + public SubGuiAbilityVariantSelect(List variants) { + this.variants = variants; + setBackground("menubg.png"); + xSize = 200; + ySize = 216; + } + + @Override + public void initGui() { + super.initGui(); + + addLabel(new GuiNpcLabel(0, "ability.selectVariant", guiLeft + 10, guiTop + 8)); + + // Build the unsorted scroll list with group headers + List scrollList = new ArrayList<>(); + scrollToVariantIndex.clear(); + + boolean hasBaseVariants = false; + boolean hasGroupedVariants = false; + + for (AbilityVariant v : variants) { + if (v.getGroup() == null) + hasBaseVariants = true; + else + hasGroupedVariants = true; + } + + // Add base (non-grouped) variants first + for (int i = 0; i < variants.size(); i++) { + if (variants.get(i).getGroup() == null) { + scrollList.add(variants.get(i).getDisplayKey()); + scrollToVariantIndex.add(i); + } + } + + // Blank separator between base and grouped variants + if (hasBaseVariants && hasGroupedVariants) { + scrollList.add(""); + scrollToVariantIndex.add(-1); + } + + // Add grouped variants with group headers + String lastGroup = null; + for (int i = 0; i < variants.size(); i++) { + AbilityVariant v = variants.get(i); + if (v.getGroup() == null) + continue; + + if (!v.getGroup().equals(lastGroup)) { + scrollList.add(v.getGroup()); + scrollToVariantIndex.add(-1); + lastGroup = v.getGroup(); + } + + scrollList.add(v.getDisplayKey()); + scrollToVariantIndex.add(i); + } + + GuiCustomScroll scroll = new GuiCustomScroll(this, 0); + scroll.guiLeft = guiLeft + 5; + scroll.guiTop = guiTop + 22; + scroll.setUnsortedList(scrollList); + scroll.setSize(190, 155); + + // Mark blank separators and group headers as non-interactive colored entries + scroll.colors.put("", 0x000000); + if (lastGroup != null) { + for (int i = 0; i < variants.size(); i++) { + String group = variants.get(i).getGroup(); + if (group != null) + scroll.colors.put(group, 0xFFFF00); // Yellow + } + } + + // Restore selection in scroll + if (selectedIndex >= 0) { + for (int s = 0; s < scrollToVariantIndex.size(); s++) { + if (scrollToVariantIndex.get(s) == selectedIndex) { + scroll.selected = s; + break; + } + } + } + + addScroll(scroll); + + // Select / Cancel buttons + addButton(new GuiNpcButton(0, guiLeft + 5, guiTop + 188, 90, 20, "gui.select")); + getButton(0).setEnabled(selectedIndex >= 0); + addButton(new GuiNpcButton(1, guiLeft + 105, guiTop + 188, 90, 20, "gui.cancel")); + } + + @Override + public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) { + if (scroll.id == 0 && scroll.selected >= 0 && scroll.selected < scrollToVariantIndex.size()) { + int variantIdx = scrollToVariantIndex.get(scroll.selected); + if (variantIdx >= 0) { + selectedIndex = variantIdx; + getButton(0).setEnabled(true); + } + } + } + + @Override + public void customScrollDoubleClicked(String selection, GuiCustomScroll scroll) { + if (selectedIndex >= 0) { + close(); + } + } + + @Override + public void buttonEvent(GuiButton guibutton) { + int id = guibutton.id; + if (id == 0 && selectedIndex >= 0) { + close(); + } else if (id == 1) { + selectedIndex = -1; + close(); + } + } + + public int getSelectedIndex() { + return selectedIndex; + } + + public List getVariants() { + return variants; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java new file mode 100644 index 000000000..b16386c32 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiDuplicateNameConfirm.java @@ -0,0 +1,47 @@ +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; + +/** + * Confirmation dialog shown when saving an ability preset with a name that already exists. + */ +public class SubGuiDuplicateNameConfirm extends SubGuiInterface { + + private boolean confirmed = false; + + public SubGuiDuplicateNameConfirm() { + setBackground("menubg.png"); + xSize = 220; + ySize = 80; + } + + @Override + public void initGui() { + super.initGui(); + + int y = guiTop + 10; + addLabel(new GuiNpcLabel(0, "ability.duplicate.name", guiLeft + 10, y)); + + y += 30; + addButton(new GuiNpcButton(0, guiLeft + 20, y, 80, 20, "gui.continue")); + addButton(new GuiNpcButton(1, guiLeft + 120, y, 80, 20, "gui.cancel")); + } + + @Override + public void buttonEvent(GuiButton guibutton) { + if (guibutton.id == 0) { + confirmed = true; + close(); + } else if (guibutton.id == 1) { + confirmed = false; + close(); + } + } + + public boolean isConfirmed() { + return confirmed; + } +} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityCharge.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityCharge.java deleted file mode 100644 index ea35797c4..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityCharge.java +++ /dev/null @@ -1,92 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityCharge; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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 + Effects - addLabel(new GuiNpcLabel(104, "ability.hitWidth", labelX, y + 5)); - addTextField(createFloatField(104, fieldX, y, 50, charge.getHitWidth())); - - addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - if (id == 150) { - setSubGui(new SubGuiAbilityEffects(charge.getEffects())); - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - charge.setEffects(result); - } - } - } - - @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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityCutter.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityCutter.java deleted file mode 100644 index a1539536d..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityCutter.java +++ /dev/null @@ -1,141 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityCutter; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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"}; - GuiNpcButton sweepModeBtn = new GuiNpcButton(106, fieldX, y, 70, 20, sweepModes, cutter.getSweepModeEnum().ordinal()); - sweepModeBtn.setHoverText("ability.hover.sweepMode"); - addButton(sweepModeBtn); - - addLabel(new GuiNpcLabel(107, "ability.piercing", col2LabelX, y + 5)); - GuiNpcButton piercingBtn = new GuiNpcButton(107, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, cutter.isPiercing() ? 1 : 0); - piercingBtn.setHoverText("ability.hover.piercing"); - addButton(piercingBtn); - - y += 24; - - // Row 5: Spin Duration (only for SPIN mode) + Effects button - if (cutter.getSweepModeEnum() == AbilityCutter.SweepMode.SPIN) { - addLabel(new GuiNpcLabel(108, "ability.duration", labelX, y + 5)); - GuiNpcTextField durationField = createIntField(108, fieldX, y, 50, cutter.getSpinDurationTicks()); - durationField.setMinMaxDefault(1, 1000, 60); - addTextField(durationField); - } - - addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 106: - cutter.setSweepModeEnum(AbilityCutter.SweepMode.values()[value]); - initGui(); // Refresh to show/hide duration field - break; - case 107: - cutter.setPiercing(value == 1); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(cutter.getEffects())); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - cutter.setEffects(result); - } - } - } - - @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.setSpinDurationTicks(field.getInteger()); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityDash.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityDash.java deleted file mode 100644 index 9d7bd63b6..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityDash.java +++ /dev/null @@ -1,65 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.type.AbilityDash; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; - -/** - * 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"}; - GuiNpcButton modeBtn = new GuiNpcButton(100, fieldX, y, 80, 20, dashModes, dash.getDashModeEnum().ordinal()); - modeBtn.setHoverText("ability.hover.dashMode"); - addButton(modeBtn); - - 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.setDashModeEnum(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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityDisc.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityDisc.java deleted file mode 100644 index 7f3d04d9e..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityDisc.java +++ /dev/null @@ -1,323 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.type.AbilityDisc; -import noppes.npcs.client.gui.SubGuiColorSelector; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * GUI for configuring Disc ability type-specific settings. - */ -public class SubGuiAbilityDisc extends SubGuiAbilityConfig { - - private final AbilityDisc disc; - private int editingVisualColorId = 0; - - public SubGuiAbilityDisc(AbilityDisc ability, IAbilityConfigCallback callback) { - super(ability, callback); - this.disc = ability; - } - - @Override - protected boolean hasVisualSettings() { - return true; - } - - @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, disc.getDamage())); - - addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5)); - addTextField(createFloatField(101, col2FieldX, y, 50, disc.getSpeed())); - - y += 24; - - // Row 2: Disc Radius + Disc Thickness - addLabel(new GuiNpcLabel(102, "ability.discRadius", labelX, y + 5)); - addTextField(createFloatField(102, fieldX, y, 50, disc.getDiscRadius())); - - addLabel(new GuiNpcLabel(103, "ability.discThickness", col2LabelX, y + 5)); - addTextField(createFloatField(103, col2FieldX, y, 50, disc.getDiscThickness())); - - y += 24; - - // Row 3: Homing + Homing Strength (only show strength if homing) - addLabel(new GuiNpcLabel(104, "ability.homing", labelX, y + 5)); - GuiNpcButton homingBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isHoming() ? 1 : 0); - homingBtn.setHoverText("ability.hover.homing"); - addButton(homingBtn); - - if (disc.isHoming()) { - addLabel(new GuiNpcLabel(105, "ability.homingStr", col2LabelX, y + 5)); - addTextField(createFloatField(105, col2FieldX, y, 50, disc.getHomingStrength())); - } - - y += 24; - - // Row 4: Boomerang + Boomerang Delay (only show delay if boomerang) - addLabel(new GuiNpcLabel(106, "ability.boomerang", labelX, y + 5)); - GuiNpcButton boomerangBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isBoomerang() ? 1 : 0); - boomerangBtn.setHoverText("ability.hover.boomerang"); - addButton(boomerangBtn); - - if (disc.isBoomerang()) { - addLabel(new GuiNpcLabel(107, "ability.boomerangDelay", col2LabelX, y + 5)); - addTextField(createIntField(107, col2FieldX, y, 50, disc.getBoomerangDelay())); - } - - y += 24; - - // Row 5: Explosive + Explosion Radius (only show radius if explosive) - addLabel(new GuiNpcLabel(108, "ability.explosive", labelX, y + 5)); - GuiNpcButton explosiveBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isExplosive() ? 1 : 0); - explosiveBtn.setHoverText("ability.hover.explosive"); - addButton(explosiveBtn); - - if (disc.isExplosive()) { - addLabel(new GuiNpcLabel(109, "ability.explosionRad", col2LabelX, y + 5)); - addTextField(createFloatField(109, col2FieldX, y, 50, disc.getExplosionRadius())); - } - - y += 24; - - // Row 6: Knockback + Max Distance - addLabel(new GuiNpcLabel(110, "ability.knockback", labelX, y + 5)); - addTextField(createFloatField(110, fieldX, y, 50, disc.getKnockback())); - - addLabel(new GuiNpcLabel(111, "ability.maxDist", col2LabelX, y + 5)); - addTextField(createFloatField(111, col2FieldX, y, 50, disc.getMaxDistance())); - - y += 24; - - // Row 7: Max Lifetime + Effects button - addLabel(new GuiNpcLabel(112, "ability.lifetime", labelX, y + 5)); - addTextField(createIntField(112, fieldX, y, 50, disc.getMaxLifetime())); - - addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void initVisualTab(int startY) { - int y = startY; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 85; - int col2LabelX = guiLeft + 180; - int col2FieldX = guiLeft + 260; - - // Row 1: Anchor Point - addLabel(new GuiNpcLabel(210, "ability.anchorPoint", labelX, y + 5)); - GuiNpcButton anchorBtn = new GuiNpcButton(210, fieldX, y, 80, 20, AnchorPoint.getDisplayNames(), disc.getAnchorPointEnum().ordinal()); - anchorBtn.setHoverText("ability.hover.anchorPoint"); - addButton(anchorBtn); - - y += 24; - - // Row 2: Inner Color + Outer Color - addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5)); - String innerHex = String.format("%06X", disc.getInnerColor() & 0xFFFFFF); - GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex); - innerColorBtn.setTextColor(disc.getInnerColor() & 0xFFFFFF); - addButton(innerColorBtn); - - addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5)); - String outerHex = String.format("%06X", disc.getOuterColor() & 0xFFFFFF); - GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex); - outerColorBtn.setTextColor(disc.getOuterColor() & 0xFFFFFF); - outerColorBtn.setEnabled(disc.isOuterColorEnabled()); - addButton(outerColorBtn); - - y += 24; - - // Row 2: Outer Color Enabled + Outer Color Width - addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5)); - addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.isOuterColorEnabled() ? 1 : 0)); - - addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5)); - GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, disc.getOuterColorWidth()); - widthField.setEnabled(disc.isOuterColorEnabled()); - addTextField(widthField); - - y += 24; - - // Row 3: Outer Color Alpha - addLabel(new GuiNpcLabel(204, "ability.outerAlpha", labelX, y + 5)); - GuiNpcTextField alphaField = createFloatField(204, fieldX, y, 55, disc.getOuterColorAlpha()); - alphaField.setEnabled(disc.isOuterColorEnabled()); - alphaField.setMinMaxDefaultFloat(0, 1, 0.5f); - addTextField(alphaField); - - y += 24; - - // Row 4: Rotation Speed - addLabel(new GuiNpcLabel(205, "ability.rotationSpeed", labelX, y + 5)); - addTextField(createFloatField(205, fieldX, y, 50, disc.getRotationSpeed())); - - y += 24; - - // Row 5: Lightning Effect Enabled - addLabel(new GuiNpcLabel(206, "ability.lightning", labelX, y + 5)); - GuiNpcButton lightningBtn = new GuiNpcButton(206, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, disc.hasLightningEffect() ? 1 : 0); - lightningBtn.setHoverText("ability.hover.lightning"); - addButton(lightningBtn); - - // Only show Lightning settings if Lightning is enabled - if (disc.hasLightningEffect()) { - y += 24; - - // Row 6: Density + Radius - addLabel(new GuiNpcLabel(207, "ability.lightningDensity", labelX, y + 5)); - GuiNpcTextField densityField = new GuiNpcTextField(207, this, fontRendererObj, fieldX, y, 55, 18, "" + disc.getLightningDensity()); - densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f); - addTextField(densityField); - - addLabel(new GuiNpcLabel(208, "ability.lightningRadius", col2LabelX, y + 5)); - GuiNpcTextField radiusField = new GuiNpcTextField(208, this, fontRendererObj, col2FieldX, y, 55, 18, "" + disc.getLightningRadius()); - radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f); - addTextField(radiusField); - } - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 104: - disc.setHoming(value == 1); - initGui(); - break; - case 106: - disc.setBoomerang(value == 1); - initGui(); - break; - case 108: - disc.setExplosive(value == 1); - initGui(); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(disc.getEffects())); - break; - } - } - - @Override - protected void handleVisualButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 200: - editingVisualColorId = 200; - setSubGui(new SubGuiColorSelector(disc.getInnerColor())); - break; - case 201: - editingVisualColorId = 201; - setSubGui(new SubGuiColorSelector(disc.getOuterColor())); - break; - case 202: - disc.setOuterColorEnabled(value == 1); - initGui(); - break; - case 206: - disc.setLightningEffect(value == 1); - initGui(); - break; - case 210: - disc.setAnchorPointEnum(AnchorPoint.fromOrdinal(value)); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) { - SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui; - int rgb = colorSelector.color & 0x00FFFFFF; - if (editingVisualColorId == 200) { - disc.setInnerColor(rgb); - } else if (editingVisualColorId == 201) { - disc.setOuterColor(rgb); - } - editingVisualColorId = 0; - initGui(); - } else if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - disc.setEffects(result); - } - } else { - super.subGuiClosed(subgui); - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 100: - disc.setDamage(parseFloat(field, disc.getDamage())); - break; - case 101: - disc.setSpeed(parseFloat(field, disc.getSpeed())); - break; - case 102: - disc.setDiscRadius(parseFloat(field, disc.getDiscRadius())); - break; - case 103: - disc.setDiscThickness(parseFloat(field, disc.getDiscThickness())); - break; - case 105: - disc.setHomingStrength(parseFloat(field, disc.getHomingStrength())); - break; - case 107: - disc.setBoomerangDelay(field.getInteger()); - break; - case 109: - disc.setExplosionRadius(parseFloat(field, disc.getExplosionRadius())); - break; - case 110: - disc.setKnockback(parseFloat(field, disc.getKnockback())); - break; - case 111: - disc.setMaxDistance(parseFloat(field, disc.getMaxDistance())); - break; - case 112: - disc.setMaxLifetime(field.getInteger()); - break; - } - } - - @Override - protected void handleVisualTextField(int id, GuiNpcTextField field) { - switch (id) { - case 203: - disc.setOuterColorWidth(parseFloat(field, disc.getOuterColorWidth())); - break; - case 204: - disc.setOuterColorAlpha(parseFloat(field, disc.getOuterColorAlpha())); - break; - case 205: - disc.setRotationSpeed(parseFloat(field, disc.getRotationSpeed())); - break; - case 207: - disc.setLightningDensity(parseFloat(field, disc.getLightningDensity())); - break; - case 208: - disc.setLightningRadius(parseFloat(field, disc.getLightningRadius())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityEffects.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityEffects.java deleted file mode 100644 index 56ddaf9f6..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityEffects.java +++ /dev/null @@ -1,202 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -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; - -import java.util.ArrayList; -import java.util.List; - -/** - * SubGui for editing ability effects (potion effects that apply to targets). - * Allows adding/removing effects and configuring type, duration, and amplifier. - */ -public class SubGuiAbilityEffects extends SubGuiInterface implements ITextfieldListener { - - private static final int MAX_EFFECTS = 5; - - // Effect type names for display - private static final String[] EFFECT_TYPE_NAMES = { - "gui.none", - "potion.moveSlowdown", - "potion.weakness", - "potion.poison", - "potion.wither", - "potion.blindness", - "potion.confusion", - "potion.hunger", - "potion.digSlowDown" - }; - - // Working copy of effects - private List effects; - private boolean cancelled = false; - - public SubGuiAbilityEffects(List existingEffects) { - // Create working copies of effects - this.effects = new ArrayList<>(); - if (existingEffects != null) { - for (AbilityEffect effect : existingEffects) { - this.effects.add(effect.copy()); - } - } - - setBackground("menubg.png"); - xSize = 280; - ySize = 180; - } - - @Override - public void initGui() { - super.initGui(); - - int y = guiTop + 8; - int labelX = guiLeft + 8; - - // Title - addLabel(new GuiNpcLabel(0, "ability.effects", labelX, y)); - y += 16; - - // Column headers - addLabel(new GuiNpcLabel(1, "gui.type", guiLeft + 10, y)); - addLabel(new GuiNpcLabel(2, "gui.duration", guiLeft + 115, y)); - addLabel(new GuiNpcLabel(3, "gui.amp", guiLeft + 175, y)); - y += 14; - - // Effect rows - for (int i = 0; i < effects.size() && i < MAX_EFFECTS; i++) { - AbilityEffect effect = effects.get(i); - int baseId = 1 + i * 10; - - // Type selector button - int typeIndex = effect.getType().ordinal(); - GuiNpcButton typeBtn = new GuiNpcButton(baseId, guiLeft + 8, y, 100, 20, EFFECT_TYPE_NAMES, typeIndex); - typeBtn.setHoverText("effect.hover.type"); - addButton(typeBtn); - - // Duration text field - GuiNpcTextField durField = new GuiNpcTextField(baseId + 1, this, fontRendererObj, - guiLeft + 112, y, 50, 20, "" + effect.getDurationTicks()); - durField.setIntegersOnly(); - durField.setMinMaxDefault(1, 12000, 60); - durField.setHoverText("effect.hover.duration"); - addTextField(durField); - - // Amplifier selector (0-10) - String[] ampValues = new String[11]; - for (int a = 0; a <= 10; a++) { - ampValues[a] = "" + a; - } - GuiNpcButton ampBtn = new GuiNpcButton(baseId + 2, guiLeft + 168, y, 40, 20, ampValues, effect.getAmplifier()); - ampBtn.setHoverText("effect.hover.amplifier"); - addButton(ampBtn); - - // Delete button - addButton(new GuiNpcButton(baseId + 3, guiLeft + 215, y, 20, 20, "X")); - - y += 24; - } - - // Add button (if space available) - if (effects.size() < MAX_EFFECTS) { - addButton(new GuiNpcButton(100, guiLeft + 8, y, 50, 20, "gui.add")); - } - - // Bottom buttons - addButton(new GuiNpcButton(65, guiLeft + 8, guiTop + ySize - 28, 60, 20, "gui.cancel")); - addButton(new GuiNpcButton(66, guiLeft + xSize - 68, guiTop + ySize - 28, 60, 20, "gui.done")); - } - - @Override - public void buttonEvent(GuiButton guibutton) { - int id = guibutton.id; - - // Add button - if (id == 100) { - if (effects.size() < MAX_EFFECTS) { - // Add new effect with default values (Slowness, 60 ticks, amp 0) - effects.add(new AbilityEffect(AbilityEffect.EffectType.SLOWNESS, 60, 0)); - initGui(); - } - return; - } - - // Cancel button - if (id == 65) { - cancelled = true; - close(); - return; - } - - // Done button - if (id == 66) { - // Remove any NONE effects before saving - effects.removeIf(e -> !e.isValid()); - cancelled = false; - close(); - return; - } - - // Effect row buttons (id >= 1 and < 100) - if (id >= 1 && id < 100) { - int effectIndex = (id - 1) / 10; - int action = (id - 1) % 10; - - if (effectIndex >= 0 && effectIndex < effects.size()) { - AbilityEffect effect = effects.get(effectIndex); - - switch (action) { - case 0: // Type selector - int typeIndex = ((GuiNpcButton) guibutton).getValue(); - effect.setType(AbilityEffect.EffectType.fromOrdinal(typeIndex)); - break; - case 2: // Amplifier selector - int amp = ((GuiNpcButton) guibutton).getValue(); - effect.setAmplifier(amp); - break; - case 3: // Delete button - effects.remove(effectIndex); - initGui(); - break; - } - } - } - } - - @Override - public void unFocused(GuiNpcTextField textField) { - int id = textField.id; - - // Duration text fields (baseId + 1) - if (id >= 2 && id < 100) { - int effectIndex = (id - 1) / 10; - int action = (id - 1) % 10; - - if (action == 1 && effectIndex >= 0 && effectIndex < effects.size()) { - effects.get(effectIndex).setDurationTicks(textField.getInteger()); - } - } - } - - /** - * Returns the resulting effects list after the dialog closes. - * Returns null if cancelled. - */ - public List getResult() { - if (cancelled) { - return null; - } - return effects; - } - - /** - * Returns true if the dialog was cancelled. - */ - public boolean wasCancelled() { - return cancelled; - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityEnergyBeam.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityEnergyBeam.java deleted file mode 100644 index 3f70e5aca..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityEnergyBeam.java +++ /dev/null @@ -1,312 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.type.AbilityEnergyBeam; -import noppes.npcs.client.gui.SubGuiColorSelector; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * GUI for configuring Energy Beam ability type-specific settings. - * Energy Beam is a homing head with trailing path (DBZ-style). - */ -public class SubGuiAbilityEnergyBeam extends SubGuiAbilityConfig { - - private final AbilityEnergyBeam beam; - private int editingVisualColorId = 0; - - public SubGuiAbilityEnergyBeam(AbilityEnergyBeam ability, IAbilityConfigCallback callback) { - super(ability, callback); - this.beam = ability; - } - - @Override - protected boolean hasVisualSettings() { - return true; - } - - @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, beam.getDamage())); - - addLabel(new GuiNpcLabel(101, "stats.speed", col2LabelX, y + 5)); - addTextField(createFloatField(101, col2FieldX, y, 50, beam.getSpeed())); - - y += 24; - - // Row 2: Beam Width + Head Size - addLabel(new GuiNpcLabel(102, "ability.beamWidth", labelX, y + 5)); - addTextField(createFloatField(102, fieldX, y, 50, beam.getBeamWidth())); - - addLabel(new GuiNpcLabel(103, "ability.headSize", col2LabelX, y + 5)); - addTextField(createFloatField(103, col2FieldX, y, 50, beam.getHeadSize())); - - y += 24; - - // Row 3: Homing + Homing Strength (only show strength if homing) - addLabel(new GuiNpcLabel(104, "ability.homing", labelX, y + 5)); - GuiNpcButton homingBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isHoming() ? 1 : 0); - homingBtn.setHoverText("ability.hover.homing"); - addButton(homingBtn); - - if (beam.isHoming()) { - addLabel(new GuiNpcLabel(105, "ability.homingStr", col2LabelX, y + 5)); - addTextField(createFloatField(105, col2FieldX, y, 50, beam.getHomingStrength())); - } - - y += 24; - - // Row 4: Max Distance (+ Homing Range only if homing) - if (beam.isHoming()) { - addLabel(new GuiNpcLabel(106, "ability.homingRange", labelX, y + 5)); - addTextField(createFloatField(106, fieldX, y, 50, beam.getHomingRange())); - } - - addLabel(new GuiNpcLabel(107, "ability.maxDist", beam.isHoming() ? col2LabelX : labelX, y + 5)); - addTextField(createFloatField(107, beam.isHoming() ? col2FieldX : fieldX, y, 50, beam.getMaxDistance())); - - y += 24; - - // Row 5: Explosive + Explosion Radius (only show radius if explosive) - addLabel(new GuiNpcLabel(108, "ability.explosive", labelX, y + 5)); - GuiNpcButton explosiveBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isExplosive() ? 1 : 0); - explosiveBtn.setHoverText("ability.hover.explosive"); - addButton(explosiveBtn); - - if (beam.isExplosive()) { - addLabel(new GuiNpcLabel(109, "ability.explosionRad", col2LabelX, y + 5)); - addTextField(createFloatField(109, col2FieldX, y, 50, beam.getExplosionRadius())); - } - - y += 24; - - // Row 6: Knockback + Max Lifetime - addLabel(new GuiNpcLabel(110, "ability.knockback", labelX, y + 5)); - addTextField(createFloatField(110, fieldX, y, 50, beam.getKnockback())); - - addLabel(new GuiNpcLabel(111, "ability.lifetime", col2LabelX, y + 5)); - addTextField(createIntField(111, col2FieldX, y, 50, beam.getMaxLifetime())); - - y += 24; - - // Row 7: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void initVisualTab(int startY) { - int y = startY; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 85; - int col2LabelX = guiLeft + 180; - int col2FieldX = guiLeft + 260; - - // Row 1: Anchor Point - addLabel(new GuiNpcLabel(210, "ability.anchorPoint", labelX, y + 5)); - GuiNpcButton anchorBtn = new GuiNpcButton(210, fieldX, y, 80, 20, AnchorPoint.getDisplayNames(), beam.getAnchorPointEnum().ordinal()); - anchorBtn.setHoverText("ability.hover.anchorPoint"); - addButton(anchorBtn); - - y += 24; - - // Row 2: Inner Color + Outer Color - addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5)); - String innerHex = String.format("%06X", beam.getInnerColor() & 0xFFFFFF); - GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex); - innerColorBtn.setTextColor(beam.getInnerColor() & 0xFFFFFF); - addButton(innerColorBtn); - - addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5)); - String outerHex = String.format("%06X", beam.getOuterColor() & 0xFFFFFF); - GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex); - outerColorBtn.setTextColor(beam.getOuterColor() & 0xFFFFFF); - outerColorBtn.setEnabled(beam.isOuterColorEnabled()); - addButton(outerColorBtn); - - y += 24; - - // Row 2: Outer Color Enabled + Outer Color Width - addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5)); - addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.isOuterColorEnabled() ? 1 : 0)); - - addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5)); - GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, beam.getOuterColorWidth()); - widthField.setEnabled(beam.isOuterColorEnabled()); - addTextField(widthField); - - y += 24; - - // Row 3: Rotation Speed - addLabel(new GuiNpcLabel(204, "ability.outerAlpha", labelX, y + 5)); - GuiNpcTextField alphaField = createFloatField(204, fieldX, y, 55, beam.getOuterColorAlpha()); - alphaField.setEnabled(beam.isOuterColorEnabled()); - alphaField.setMinMaxDefaultFloat(0, 1, 0.5f); - addTextField(alphaField); - - addLabel(new GuiNpcLabel(205, "ability.rotationSpeed", col2LabelX, y + 5)); - addTextField(createFloatField(205, col2FieldX, y, 50, beam.getRotationSpeed())); - - y += 24; - - // Row 4: Lightning Effect Enabled (only affects head) - addLabel(new GuiNpcLabel(206, "ability.lightning", labelX, y + 5)); - GuiNpcButton lightningBtn = new GuiNpcButton(206, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, beam.hasLightningEffect() ? 1 : 0); - lightningBtn.setHoverText("ability.hover.lightning"); - addButton(lightningBtn); - - // Only show Lightning settings if Lightning is enabled - if (beam.hasLightningEffect()) { - y += 24; - - // Row 5: Density + Radius - addLabel(new GuiNpcLabel(207, "ability.lightningDensity", labelX, y + 5)); - GuiNpcTextField densityField = new GuiNpcTextField(207, this, fontRendererObj, fieldX, y, 55, 18, "" + beam.getLightningDensity()); - densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f); - addTextField(densityField); - - addLabel(new GuiNpcLabel(208, "ability.lightningRadius", col2LabelX, y + 5)); - GuiNpcTextField radiusField = new GuiNpcTextField(208, this, fontRendererObj, col2FieldX, y, 55, 18, "" + beam.getLightningRadius()); - radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f); - addTextField(radiusField); - } - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 104: - beam.setHoming(value == 1); - initGui(); - break; - case 108: - beam.setExplosive(value == 1); - initGui(); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(beam.getEffects())); - break; - } - } - - @Override - protected void handleVisualButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 200: - editingVisualColorId = 200; - setSubGui(new SubGuiColorSelector(beam.getInnerColor())); - break; - case 201: - editingVisualColorId = 201; - setSubGui(new SubGuiColorSelector(beam.getOuterColor())); - break; - case 202: - beam.setOuterColorEnabled(value == 1); - initGui(); - break; - case 206: - beam.setLightningEffect(value == 1); - initGui(); - break; - case 210: - beam.setAnchorPointEnum(AnchorPoint.fromOrdinal(value)); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) { - SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui; - int rgb = colorSelector.color & 0x00FFFFFF; - if (editingVisualColorId == 200) { - beam.setInnerColor(rgb); - } else if (editingVisualColorId == 201) { - beam.setOuterColor(rgb); - } - editingVisualColorId = 0; - initGui(); - } else if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - beam.setEffects(result); - } - } else { - super.subGuiClosed(subgui); - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 100: - beam.setDamage(parseFloat(field, beam.getDamage())); - break; - case 101: - beam.setSpeed(parseFloat(field, beam.getSpeed())); - break; - case 102: - beam.setBeamWidth(parseFloat(field, beam.getBeamWidth())); - break; - case 103: - beam.setHeadSize(parseFloat(field, beam.getHeadSize())); - break; - case 105: - beam.setHomingStrength(parseFloat(field, beam.getHomingStrength())); - break; - case 106: - beam.setHomingRange(parseFloat(field, beam.getHomingRange())); - break; - case 107: - beam.setMaxDistance(parseFloat(field, beam.getMaxDistance())); - break; - case 109: - beam.setExplosionRadius(parseFloat(field, beam.getExplosionRadius())); - break; - case 110: - beam.setKnockback(parseFloat(field, beam.getKnockback())); - break; - case 111: - beam.setMaxLifetime(field.getInteger()); - break; - } - } - - @Override - protected void handleVisualTextField(int id, GuiNpcTextField field) { - switch (id) { - case 203: - beam.setOuterColorWidth(parseFloat(field, beam.getOuterColorWidth())); - break; - case 204: - beam.setOuterColorAlpha(parseFloat(field, beam.getOuterColorAlpha())); - break; - case 205: - beam.setRotationSpeed(parseFloat(field, beam.getRotationSpeed())); - break; - case 207: - beam.setLightningDensity(parseFloat(field, beam.getLightningDensity())); - break; - case 208: - beam.setLightningRadius(parseFloat(field, beam.getLightningRadius())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityGuard.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityGuard.java deleted file mode 100644 index 0d2ec667b..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityGuard.java +++ /dev/null @@ -1,143 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityGuard; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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: Duration + Damage Reduction - addLabel(new GuiNpcLabel(99, "ability.duration", labelX, y + 5)); - GuiNpcTextField durationField = createIntField(99, fieldX, y, 50, guard.getDurationTicks()); - durationField.setMinMaxDefault(1, 1000, 60); - addTextField(durationField); - - addLabel(new GuiNpcLabel(100, "ability.dmgReduce", col2LabelX, y + 5)); - addTextField(createFloatField(100, col2FieldX, y, 50, guard.getDamageReduction())); - - y += 24; - - // Row 2: Can Counter + Counter Type - addLabel(new GuiNpcLabel(101, "ability.canCounter", labelX, y + 5)); - GuiNpcButton canCounterBtn = new GuiNpcButton(101, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, guard.isCanCounter() ? 1 : 0); - canCounterBtn.setHoverText("ability.hover.canCounter"); - addButton(canCounterBtn); - - addLabel(new GuiNpcLabel(102, "ability.counterType", col2LabelX, y + 5)); - String[] types = {"Flat", "Percent"}; - GuiNpcButton counterTypeButton = new GuiNpcButton(102, col2FieldX, y, 60, 20, types, guard.getCounterTypeEnum().ordinal()); - counterTypeButton.setHoverText("ability.hover.counterType"); - 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); - - y += 24; - - // Row 5: Effects button (applies on counter) - GuiNpcButton effectsBtn = new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects"); - effectsBtn.setEnabled(guard.isCanCounter()); - addButton(effectsBtn); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - switch (id) { - case 101: - guard.setCanCounter(button.getValue() == 1); - initGui(); - break; - case 102: - guard.setCounterTypeEnum(AbilityGuard.CounterType.values()[button.getValue()]); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(guard.getEffects())); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - guard.setEffects(result); - } - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 99: - guard.setDurationTicks(field.getInteger()); - break; - 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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHazard.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHazard.java deleted file mode 100644 index 5b8be7976..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHazard.java +++ /dev/null @@ -1,159 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityHazard; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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: Duration + Shape - addLabel(new GuiNpcLabel(99, "ability.duration", labelX, y + 5)); - GuiNpcTextField durationField = createIntField(99, fieldX, y, 50, hazard.getDurationTicks()); - durationField.setMinMaxDefault(1, 2000, 100); - addTextField(durationField); - - addLabel(new GuiNpcLabel(100, "ability.shape", col2LabelX, y + 5)); - String[] shapes = {"Circle", "Ring", "Cone"}; - GuiNpcButton shapeBtn = new GuiNpcButton(100, col2FieldX, y, 55, 20, shapes, hazard.getShapeEnum().ordinal()); - shapeBtn.setHoverText("ability.hover.shape"); - addButton(shapeBtn); - - y += 24; - - // Row 2: Placement - addLabel(new GuiNpcLabel(101, "ability.placement", labelX, y + 5)); - String[] placements = {"Caster", "Target", "FollowCast", "FollowTgt"}; - GuiNpcButton placementBtn = new GuiNpcButton(101, fieldX, y, 70, 20, placements, hazard.getPlacementEnum().ordinal()); - placementBtn.setHoverText("ability.hover.placement"); - addButton(placementBtn); - - 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 Second + Damage Interval - addLabel(new GuiNpcLabel(104, "ability.dmgPerSec", labelX, y + 5)); - addTextField(createFloatField(104, fieldX, y, 50, hazard.getDamagePerSecond())); - - 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)); - GuiNpcButton affectsCasterBtn = new GuiNpcButton(109, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, hazard.isAffectsCaster() ? 1 : 0); - affectsCasterBtn.setHoverText("ability.hover.affectsCaster"); - addButton(affectsCasterBtn); - - y += 24; - - // Row 6: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 100: - hazard.setShapeEnum(AbilityHazard.HazardShape.values()[value]); - break; - case 101: - hazard.setPlacementEnum(AbilityHazard.PlacementMode.values()[value]); - break; - case 109: - hazard.setAffectsCaster(value == 1); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(hazard.getEffects())); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - hazard.setEffects(result); - } - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 99: - hazard.setDurationTicks(field.getInteger()); - break; - case 102: - hazard.setRadius(parseFloat(field, hazard.getRadius())); - break; - case 103: - hazard.setInnerRadius(parseFloat(field, hazard.getInnerRadius())); - break; - case 104: - hazard.setDamagePerSecond(parseFloat(field, hazard.getDamagePerSecond())); - 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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHeal.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHeal.java deleted file mode 100644 index 490b4773a..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHeal.java +++ /dev/null @@ -1,106 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.type.AbilityHeal; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; - -/** - * 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: Instant Heal + Duration (only shown if not instant) - addLabel(new GuiNpcLabel(103, "dialog.instant", labelX, y + 5)); - GuiNpcButton instantBtn = new GuiNpcButton(103, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isInstantHeal() ? 1 : 0); - instantBtn.setHoverText("ability.hover.instant"); - addButton(instantBtn); - - if (!heal.isInstantHeal()) { - addLabel(new GuiNpcLabel(99, "ability.duration", col2LabelX, y + 5)); - GuiNpcTextField durationField = createIntField(99, col2FieldX, y, 50, heal.getDurationTicks()); - durationField.setMinMaxDefault(1, 1000, 60); - addTextField(durationField); - } - - y += 24; - - // Row 2: 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 3: Heal Radius - addLabel(new GuiNpcLabel(102, "ability.healRadius", labelX, y + 5)); - addTextField(createFloatField(102, fieldX, y, 50, heal.getHealRadius())); - - y += 24; - - // Row 4: Heal Self + Heal Allies - addLabel(new GuiNpcLabel(104, "ability.healSelf", labelX, y + 5)); - GuiNpcButton healSelfBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isHealSelf() ? 1 : 0); - healSelfBtn.setHoverText("ability.hover.healSelf"); - addButton(healSelfBtn); - - addLabel(new GuiNpcLabel(105, "ability.healAllies", col2LabelX, y + 5)); - GuiNpcButton healAlliesBtn = new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, heal.isHealAllies() ? 1 : 0); - healAlliesBtn.setHoverText("ability.hover.healAllies"); - addButton(healAlliesBtn); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 103: - heal.setInstantHeal(value == 1); - initGui(); // Refresh to show/hide duration field - 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 99: - heal.setDurationTicks(field.getInteger()); - break; - 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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHeavyHit.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHeavyHit.java deleted file mode 100644 index 897a4af1f..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityHeavyHit.java +++ /dev/null @@ -1,76 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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; - - // Row 1: Damage + Knockback - addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5)); - addTextField(createFloatField(100, fieldX, y, 50, heavyHit.getDamage())); - - addLabel(new GuiNpcLabel(102, "ability.knockback", col2LabelX, y + 5)); - addTextField(createFloatField(102, guiLeft + 205, y, 50, heavyHit.getKnockback())); - - y += 24; - - // Row 2: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - if (id == 150) { - setSubGui(new SubGuiAbilityEffects(heavyHit.getEffects())); - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - heavyHit.setEffects(result); - } - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 100: - heavyHit.setDamage(parseFloat(field, heavyHit.getDamage())); - break; - case 102: - heavyHit.setKnockback(parseFloat(field, heavyHit.getKnockback())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityLaserShot.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityLaserShot.java deleted file mode 100644 index b594a83c7..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityLaserShot.java +++ /dev/null @@ -1,268 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityLaserShot; -import noppes.npcs.client.gui.SubGuiColorSelector; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * GUI for configuring Laser Shot ability type-specific settings. - */ -public class SubGuiAbilityLaserShot extends SubGuiAbilityConfig { - - private final AbilityLaserShot laser; - private int editingVisualColorId = 0; - - public SubGuiAbilityLaserShot(AbilityLaserShot ability, IAbilityConfigCallback callback) { - super(ability, callback); - this.laser = ability; - } - - @Override - protected boolean hasVisualSettings() { - return true; - } - - @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 + Laser Width - addLabel(new GuiNpcLabel(100, "enchantment.damage", labelX, y + 5)); - addTextField(createFloatField(100, fieldX, y, 50, laser.getDamage())); - - addLabel(new GuiNpcLabel(101, "ability.laserWidth", col2LabelX, y + 5)); - addTextField(createFloatField(101, col2FieldX, y, 50, laser.getLaserWidth())); - - y += 24; - - // Row 2: Expansion Speed + Linger Ticks - addLabel(new GuiNpcLabel(102, "ability.expansionSpeed", labelX, y + 5)); - addTextField(createFloatField(102, fieldX, y, 50, laser.getExpansionSpeed())); - - addLabel(new GuiNpcLabel(103, "ability.lingerTicks", col2LabelX, y + 5)); - addTextField(createIntField(103, col2FieldX, y, 50, laser.getLingerTicks())); - - y += 24; - - // Row 3: Max Distance + Max Lifetime - addLabel(new GuiNpcLabel(104, "ability.maxDist", labelX, y + 5)); - addTextField(createFloatField(104, fieldX, y, 50, laser.getMaxDistance())); - - addLabel(new GuiNpcLabel(105, "ability.lifetime", col2LabelX, y + 5)); - addTextField(createIntField(105, col2FieldX, y, 50, laser.getMaxLifetime())); - - y += 24; - - // Row 4: Explosive + Explosion Radius (only show radius if explosive) - addLabel(new GuiNpcLabel(106, "ability.explosive", labelX, y + 5)); - GuiNpcButton explosiveBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, laser.isExplosive() ? 1 : 0); - explosiveBtn.setHoverText("ability.hover.explosive"); - addButton(explosiveBtn); - - if (laser.isExplosive()) { - addLabel(new GuiNpcLabel(107, "ability.explosionRad", col2LabelX, y + 5)); - addTextField(createFloatField(107, col2FieldX, y, 50, laser.getExplosionRadius())); - } - - y += 24; - - // Row 5: Knockback + Knockback Up - addLabel(new GuiNpcLabel(108, "ability.knockback", labelX, y + 5)); - addTextField(createFloatField(108, fieldX, y, 50, laser.getKnockback())); - - addLabel(new GuiNpcLabel(109, "ability.knockbackUp", col2LabelX, y + 5)); - addTextField(createFloatField(109, col2FieldX, y, 50, laser.getKnockbackUp())); - - y += 24; - - // Row 6: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void initVisualTab(int startY) { - int y = startY; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 85; - int col2LabelX = guiLeft + 180; - int col2FieldX = guiLeft + 260; - - // Row 1: Inner Color + Outer Color - addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5)); - String innerHex = String.format("%06X", laser.getInnerColor() & 0xFFFFFF); - GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex); - innerColorBtn.setTextColor(laser.getInnerColor() & 0xFFFFFF); - addButton(innerColorBtn); - - addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5)); - String outerHex = String.format("%06X", laser.getOuterColor() & 0xFFFFFF); - GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex); - outerColorBtn.setTextColor(laser.getOuterColor() & 0xFFFFFF); - outerColorBtn.setEnabled(laser.isOuterColorEnabled()); - addButton(outerColorBtn); - - y += 24; - - // Row 2: Outer Color Enabled + Outer Color Width - addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5)); - addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, laser.isOuterColorEnabled() ? 1 : 0)); - - addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5)); - GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, laser.getOuterColorWidth()); - widthField.setEnabled(laser.isOuterColorEnabled()); - addTextField(widthField); - - y += 24; - - // Row 3: Lightning Effect Enabled - addLabel(new GuiNpcLabel(204, "ability.outerAlpha", labelX, y + 5)); - GuiNpcTextField alphaField = createFloatField(204, fieldX, y, 55, laser.getOuterColorAlpha()); - alphaField.setEnabled(laser.isOuterColorEnabled()); - alphaField.setMinMaxDefaultFloat(0, 1, 0.5f); - addTextField(alphaField); - - addLabel(new GuiNpcLabel(205, "ability.lightning", col2LabelX, y + 5)); - GuiNpcButton lightningBtn = new GuiNpcButton(205, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, laser.hasLightningEffect() ? 1 : 0); - lightningBtn.setHoverText("ability.hover.lightning"); - addButton(lightningBtn); - - // Only show Lightning settings if Lightning is enabled - if (laser.hasLightningEffect()) { - y += 24; - - // Row 4: Density + Radius - addLabel(new GuiNpcLabel(206, "ability.lightningDensity", labelX, y + 5)); - GuiNpcTextField densityField = new GuiNpcTextField(206, this, fontRendererObj, fieldX, y, 55, 18, "" + laser.getLightningDensity()); - densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f); - addTextField(densityField); - - addLabel(new GuiNpcLabel(207, "ability.lightningRadius", col2LabelX, y + 5)); - GuiNpcTextField radiusField = new GuiNpcTextField(207, this, fontRendererObj, col2FieldX, y, 55, 18, "" + laser.getLightningRadius()); - radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f); - addTextField(radiusField); - } - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 106: - laser.setExplosive(value == 1); - initGui(); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(laser.getEffects())); - break; - } - } - - @Override - protected void handleVisualButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 200: - editingVisualColorId = 200; - setSubGui(new SubGuiColorSelector(laser.getInnerColor())); - break; - case 201: - editingVisualColorId = 201; - setSubGui(new SubGuiColorSelector(laser.getOuterColor())); - break; - case 202: - laser.setOuterColorEnabled(value == 1); - initGui(); - break; - case 205: - laser.setLightningEffect(value == 1); - initGui(); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) { - SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui; - int rgb = colorSelector.color & 0x00FFFFFF; - if (editingVisualColorId == 200) { - laser.setInnerColor(rgb); - } else if (editingVisualColorId == 201) { - laser.setOuterColor(rgb); - } - editingVisualColorId = 0; - initGui(); - } else if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - laser.setEffects(result); - } - } else { - super.subGuiClosed(subgui); - } - } - - @Override - protected void handleVisualTextField(int id, GuiNpcTextField field) { - switch (id) { - case 203: - laser.setOuterColorWidth(parseFloat(field, laser.getOuterColorWidth())); - break; - case 204: - laser.setOuterColorAlpha(parseFloat(field, laser.getOuterColorAlpha())); - break; - case 206: - laser.setLightningDensity(parseFloat(field, laser.getLightningDensity())); - break; - case 207: - laser.setLightningRadius(parseFloat(field, laser.getLightningRadius())); - break; - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 100: - laser.setDamage(parseFloat(field, laser.getDamage())); - break; - case 101: - laser.setLaserWidth(parseFloat(field, laser.getLaserWidth())); - break; - case 102: - laser.setExpansionSpeed(parseFloat(field, laser.getExpansionSpeed())); - break; - case 103: - laser.setLingerTicks(field.getInteger()); - break; - case 104: - laser.setMaxDistance(parseFloat(field, laser.getMaxDistance())); - break; - case 105: - laser.setMaxLifetime(field.getInteger()); - break; - case 107: - laser.setExplosionRadius(parseFloat(field, laser.getExplosionRadius())); - break; - case 108: - laser.setKnockback(parseFloat(field, laser.getKnockback())); - break; - case 109: - laser.setKnockbackUp(parseFloat(field, laser.getKnockbackUp())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityOrb.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityOrb.java deleted file mode 100644 index 780661c6f..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityOrb.java +++ /dev/null @@ -1,294 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.AnchorPoint; -import kamkeel.npcs.controllers.data.ability.type.AbilityOrb; -import noppes.npcs.client.gui.SubGuiColorSelector; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * GUI for configuring Orb ability type-specific settings. - */ -public class SubGuiAbilityOrb extends SubGuiAbilityConfig { - - private final AbilityOrb orb; - private int editingVisualColorId = 0; - - public SubGuiAbilityOrb(AbilityOrb ability, IAbilityConfigCallback callback) { - super(ability, callback); - this.orb = ability; - } - - @Override - protected boolean hasVisualSettings() { - return true; - } - - @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 (only show strength if homing) - addLabel(new GuiNpcLabel(104, "ability.homing", labelX, y + 5)); - GuiNpcButton homingBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isHoming() ? 1 : 0); - homingBtn.setHoverText("ability.hover.homing"); - addButton(homingBtn); - - if (orb.isHoming()) { - addLabel(new GuiNpcLabel(105, "ability.homingStr", col2LabelX, y + 5)); - addTextField(createFloatField(105, col2FieldX, y, 50, orb.getHomingStrength())); - } - - y += 24; - - // Row 4: Explosive + Explosion Radius (only show radius if explosive) - addLabel(new GuiNpcLabel(106, "ability.explosive", labelX, y + 5)); - GuiNpcButton explosiveBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isExplosive() ? 1 : 0); - explosiveBtn.setHoverText("ability.hover.explosive"); - addButton(explosiveBtn); - - if (orb.isExplosive()) { - 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())); - - y += 24; - - // Row 6: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void initVisualTab(int startY) { - int y = startY; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 85; - int col2LabelX = guiLeft + 180; - int col2FieldX = guiLeft + 260; - - // Row 1: Anchor Point - addLabel(new GuiNpcLabel(210, "ability.anchorPoint", labelX, y + 5)); - GuiNpcButton anchorBtn = new GuiNpcButton(210, fieldX, y, 80, 20, AnchorPoint.getDisplayNames(), orb.getAnchorPointEnum().ordinal()); - anchorBtn.setHoverText("ability.hover.anchorPoint"); - addButton(anchorBtn); - - y += 24; - - // Row 2: Inner Color + Rotation Speed - addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5)); - String innerHex = String.format("%06X", orb.getInnerColor() & 0xFFFFFF); - GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex); - innerColorBtn.setTextColor(orb.getInnerColor() & 0xFFFFFF); - addButton(innerColorBtn); - - addLabel(new GuiNpcLabel(205, "ability.rotationSpeed", col2LabelX, y + 5)); - addTextField(createFloatField(205, col2FieldX, y, 55, orb.getRotationSpeed())); - - y += 24; - - // Row 3: Outer Glow Enabled - addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5)); - addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.isOuterColorEnabled() ? 1 : 0)); - - // Only show Outer Color and Width if Outer Glow is enabled - if (orb.isOuterColorEnabled()) { - addLabel(new GuiNpcLabel(204, "ability.outerAlpha", col2LabelX, y + 5)); - GuiNpcTextField alphaField = createFloatField(204, col2FieldX, y, 55, orb.getOuterColorAlpha()); - alphaField.setEnabled(orb.isOuterColorEnabled()); - alphaField.setMinMaxDefaultFloat(0, 1, 0.5f); - addTextField(alphaField); - - y += 24; - - // Row 4: Outer Color + Outer Width - addLabel(new GuiNpcLabel(201, "ability.outerColor", labelX, y + 5)); - String outerHex = String.format("%06X", orb.getOuterColor() & 0xFFFFFF); - GuiNpcButton outerColorBtn = new GuiNpcButton(201, fieldX, y, 55, 20, outerHex); - outerColorBtn.setTextColor(orb.getOuterColor() & 0xFFFFFF); - addButton(outerColorBtn); - - addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5)); - addTextField(createFloatField(203, col2FieldX, y, 55, orb.getOuterColorWidth())); - } - - y += 24; - - // Row 5: Lightning Effect Enabled - addLabel(new GuiNpcLabel(206, "ability.lightning", labelX, y + 5)); - GuiNpcButton lightningBtn = new GuiNpcButton(206, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, orb.hasLightningEffect() ? 1 : 0); - lightningBtn.setHoverText("ability.hover.lightning"); - addButton(lightningBtn); - - // Only show Lightning settings if Lightning is enabled - if (orb.hasLightningEffect()) { - y += 24; - - // Row 61: Density + Radius - addLabel(new GuiNpcLabel(207, "ability.lightningDensity", labelX, y + 5)); - GuiNpcTextField densityField = new GuiNpcTextField(207, this, fontRendererObj, fieldX, y, 55, 18, "" + orb.getLightningDensity()); - densityField.setMinMaxDefaultFloat(0.01f, 5.0f, 0.15f); - addTextField(densityField); - - addLabel(new GuiNpcLabel(208, "ability.lightningRadius", col2LabelX, y + 5)); - GuiNpcTextField radiusField = new GuiNpcTextField(208, this, fontRendererObj, col2FieldX, y, 55, 18, "" + orb.getLightningRadius()); - radiusField.setMinMaxDefaultFloat(0.1f, 10.0f, 0.5f); - addTextField(radiusField); - } - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 104: - orb.setHoming(value == 1); - initGui(); - break; - case 106: - orb.setExplosive(value == 1); - initGui(); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(orb.getEffects())); - break; - } - } - - @Override - protected void handleVisualButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 200: - editingVisualColorId = 200; - setSubGui(new SubGuiColorSelector(orb.getInnerColor())); - break; - case 201: - editingVisualColorId = 201; - setSubGui(new SubGuiColorSelector(orb.getOuterColor())); - break; - case 202: - orb.setOuterColorEnabled(value == 1); - initGui(); - break; - case 206: - orb.setLightningEffect(value == 1); - initGui(); - break; - case 210: - orb.setAnchorPointEnum(AnchorPoint.fromOrdinal(value)); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) { - SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui; - int rgb = colorSelector.color & 0x00FFFFFF; - if (editingVisualColorId == 200) { - orb.setInnerColor(rgb); - } else if (editingVisualColorId == 201) { - orb.setOuterColor(rgb); - } - editingVisualColorId = 0; - initGui(); - } else if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - orb.setEffects(result); - } - } else { - super.subGuiClosed(subgui); - } - } - - @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; - } - } - - @Override - protected void handleVisualTextField(int id, GuiNpcTextField field) { - switch (id) { - case 203: - orb.setOuterColorWidth(parseFloat(field, orb.getOuterColorWidth())); - break; - case 204: - orb.setOuterColorAlpha(parseFloat(field, orb.getOuterColorAlpha())); - break; - case 205: - orb.setRotationSpeed(parseFloat(field, orb.getRotationSpeed())); - break; - case 207: - orb.setLightningDensity(parseFloat(field, orb.getLightningDensity())); - break; - case 208: - orb.setLightningRadius(parseFloat(field, orb.getLightningRadius())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityProjectile.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityProjectile.java deleted file mode 100644 index fe66fa242..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityProjectile.java +++ /dev/null @@ -1,145 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityProjectile; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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 (only show radius if explosive) - addLabel(new GuiNpcLabel(104, "ability.explosive", labelX, y + 5)); - GuiNpcButton explosiveBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, projectile.isExplosive() ? 1 : 0); - explosiveBtn.setHoverText("ability.hover.explosive"); - addButton(explosiveBtn); - - if (projectile.isExplosive()) { - addLabel(new GuiNpcLabel(105, "ability.explosionRad", col2LabelX, y + 5)); - addTextField(createFloatField(105, col2FieldX, y, 50, projectile.getExplosionRadius())); - } - - y += 24; - - // Row 4: Homing + Homing Strength (only show strength if homing) - addLabel(new GuiNpcLabel(106, "ability.homing", labelX, y + 5)); - GuiNpcButton homingBtn = new GuiNpcButton(106, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, projectile.isHoming() ? 1 : 0); - homingBtn.setHoverText("ability.hover.homing"); - addButton(homingBtn); - - if (projectile.isHoming()) { - addLabel(new GuiNpcLabel(107, "ability.homingStr", col2LabelX, y + 5)); - addTextField(createFloatField(107, col2FieldX, y, 50, projectile.getHomingStrength())); - } - - y += 24; - - // Row 5: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @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); - initGui(); - break; - case 106: - projectile.setHoming(value == 1); - initGui(); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(projectile.getEffects())); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - projectile.setEffects(result); - } - } - } - - @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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityShockwave.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityShockwave.java deleted file mode 100644 index 48c2c5295..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityShockwave.java +++ /dev/null @@ -1,95 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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: Max Targets + Effects button - addLabel(new GuiNpcLabel(104, "ability.maxTargets", labelX, y + 5)); - addTextField(createIntField(104, fieldX, y, 50, shockwave.getMaxTargets())); - - addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects")); - - y += 24; - addLabel(new GuiNpcLabel(105, "ability.shockwaveFalloff", labelX, y + 5)); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - if (id == 150) { - setSubGui(new SubGuiAbilityEffects(shockwave.getEffects())); - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - shockwave.setEffects(result); - } - } - } - - @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 104: - shockwave.setMaxTargets(field.getInteger()); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilitySlam.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilitySlam.java deleted file mode 100644 index 4e020829b..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilitySlam.java +++ /dev/null @@ -1,98 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilitySlam; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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 + Effects - addLabel(new GuiNpcLabel(104, "ability.leapHeight", labelX, y + 5)); - addTextField(createFloatField(104, fieldX, y, 50, slam.getLeapHeight())); - - addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - if (id == 150) { - setSubGui(new SubGuiAbilityEffects(slam.getEffects())); - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - slam.setEffects(result); - } - } - } - - @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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilitySweeper.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilitySweeper.java deleted file mode 100644 index 1561b408a..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilitySweeper.java +++ /dev/null @@ -1,219 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilitySweeper; -import noppes.npcs.client.gui.SubGuiColorSelector; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * GUI for configuring Sweeper ability type-specific settings. - * Sweeper is a low rotating beam that players can jump over. - */ -public class SubGuiAbilitySweeper extends SubGuiAbilityConfig { - - private final AbilitySweeper sweeper; - private int editingVisualColorId = 0; - - public SubGuiAbilitySweeper(AbilitySweeper ability, IAbilityConfigCallback callback) { - super(ability, callback); - this.sweeper = ability; - } - - @Override - protected boolean hasVisualSettings() { - return true; - } - - @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, sweeper.getDamage())); - - addLabel(new GuiNpcLabel(101, "ability.dmgInterval", col2LabelX, y + 5)); - addTextField(createIntField(101, col2FieldX, y, 50, sweeper.getDamageInterval())); - - y += 24; - - // Row 2: Beam Length + Beam Width - addLabel(new GuiNpcLabel(102, "ability.beamLength", labelX, y + 5)); - addTextField(createFloatField(102, fieldX, y, 50, sweeper.getBeamLength())); - - addLabel(new GuiNpcLabel(103, "ability.beamWidth", col2LabelX, y + 5)); - addTextField(createFloatField(103, col2FieldX, y, 50, sweeper.getBeamWidth())); - - y += 24; - - // Row 3: Beam Height + Sweep Speed - addLabel(new GuiNpcLabel(104, "ability.beamHeight", labelX, y + 5)); - addTextField(createFloatField(104, fieldX, y, 50, sweeper.getBeamHeight())); - - addLabel(new GuiNpcLabel(105, "ability.sweepSpeed", col2LabelX, y + 5)); - addTextField(createFloatField(105, col2FieldX, y, 50, sweeper.getSweepSpeed())); - - y += 24; - - // Row 4: Number of Rotations + Piercing - addLabel(new GuiNpcLabel(106, "ability.rotations", labelX, y + 5)); - addTextField(createIntField(106, fieldX, y, 50, sweeper.getNumberOfRotations())); - - addLabel(new GuiNpcLabel(107, "ability.piercing", col2LabelX, y + 5)); - GuiNpcButton piercingBtn = new GuiNpcButton(107, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, sweeper.isPiercing() ? 1 : 0); - piercingBtn.setHoverText("ability.hover.piercing"); - addButton(piercingBtn); - - y += 24; - - // Row 5: Lock On Target - addLabel(new GuiNpcLabel(108, "ability.lockTarget", labelX, y + 5)); - GuiNpcButton lockTargetBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, sweeper.isLockOnTarget() ? 1 : 0); - lockTargetBtn.setHoverText("ability.hover.lockTarget"); - addButton(lockTargetBtn); - - y += 24; - - // Row 6: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void initVisualTab(int startY) { - int y = startY; - int labelX = guiLeft + 8; - int fieldX = guiLeft + 85; - int col2LabelX = guiLeft + 180; - int col2FieldX = guiLeft + 260; - - // Row 1: Inner Color + Outer Color - addLabel(new GuiNpcLabel(200, "ability.innerColor", labelX, y + 5)); - String innerHex = String.format("%06X", sweeper.getInnerColor() & 0xFFFFFF); - GuiNpcButton innerColorBtn = new GuiNpcButton(200, fieldX, y, 55, 20, innerHex); - innerColorBtn.setTextColor(sweeper.getInnerColor() & 0xFFFFFF); - addButton(innerColorBtn); - - addLabel(new GuiNpcLabel(201, "ability.outerColor", col2LabelX, y + 5)); - String outerHex = String.format("%06X", sweeper.getOuterColor() & 0xFFFFFF); - GuiNpcButton outerColorBtn = new GuiNpcButton(201, col2FieldX, y, 55, 20, outerHex); - outerColorBtn.setTextColor(sweeper.getOuterColor() & 0xFFFFFF); - outerColorBtn.setEnabled(sweeper.isOuterColorEnabled()); - addButton(outerColorBtn); - - y += 24; - - // Row 2: Outer Color Enabled + Outer Color Width - addLabel(new GuiNpcLabel(202, "ability.outerEnabled", labelX, y + 5)); - addButton(new GuiNpcButton(202, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, sweeper.isOuterColorEnabled() ? 1 : 0)); - - addLabel(new GuiNpcLabel(203, "ability.outerWidth", col2LabelX, y + 5)); - GuiNpcTextField widthField = createFloatField(203, col2FieldX, y, 55, sweeper.getOuterColorWidth()); - widthField.setEnabled(sweeper.isOuterColorEnabled()); - addTextField(widthField); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 107: - sweeper.setPiercing(value == 1); - break; - case 108: - sweeper.setLockOnTarget(value == 1); - break; - case 150: - setSubGui(new SubGuiAbilityEffects(sweeper.getEffects())); - break; - } - } - - @Override - protected void handleVisualButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 200: - editingVisualColorId = 200; - setSubGui(new SubGuiColorSelector(sweeper.getInnerColor())); - break; - case 201: - editingVisualColorId = 201; - setSubGui(new SubGuiColorSelector(sweeper.getOuterColor())); - break; - case 202: - sweeper.setOuterColorEnabled(value == 1); - initGui(); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - if (subgui instanceof SubGuiColorSelector && editingVisualColorId != 0) { - SubGuiColorSelector colorSelector = (SubGuiColorSelector) subgui; - int rgb = colorSelector.color & 0x00FFFFFF; - if (editingVisualColorId == 200) { - sweeper.setInnerColor(rgb); - } else if (editingVisualColorId == 201) { - sweeper.setOuterColor(rgb); - } - editingVisualColorId = 0; - initGui(); - } else if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - sweeper.setEffects(result); - } - } else { - super.subGuiClosed(subgui); - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 100: - sweeper.setDamage(parseFloat(field, sweeper.getDamage())); - break; - case 101: - sweeper.setDamageInterval(field.getInteger()); - break; - case 102: - sweeper.setBeamLength(parseFloat(field, sweeper.getBeamLength())); - break; - case 103: - sweeper.setBeamWidth(parseFloat(field, sweeper.getBeamWidth())); - break; - case 104: - sweeper.setBeamHeight(parseFloat(field, sweeper.getBeamHeight())); - break; - case 105: - sweeper.setSweepSpeed(parseFloat(field, sweeper.getSweepSpeed())); - break; - case 106: - sweeper.setNumberOfRotations(field.getInteger()); - break; - } - } - - @Override - protected void handleVisualTextField(int id, GuiNpcTextField field) { - switch (id) { - case 203: - sweeper.setOuterColorWidth(parseFloat(field, sweeper.getOuterColorWidth())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityTeleport.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityTeleport.java deleted file mode 100644 index 4b23b0ca0..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityTeleport.java +++ /dev/null @@ -1,165 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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.getModeEnum().ordinal())); - - y += 24; - - switch (teleport.getModeEnum()) { - 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)); - GuiNpcButton losBtn1 = new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isRequireLineOfSight() ? 1 : 0); - losBtn1.setHoverText("ability.hover.lineOfSight"); - addButton(losBtn1); - 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)); - GuiNpcButton losBtn2 = new GuiNpcButton(105, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isRequireLineOfSight() ? 1 : 0); - losBtn2.setHoverText("ability.hover.lineOfSight"); - addButton(losBtn2); - 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)); - GuiNpcButton dmgStartBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isDamageAtStart() ? 1 : 0); - dmgStartBtn.setHoverText("ability.hover.dmgAtStart"); - addButton(dmgStartBtn); - - addLabel(new GuiNpcLabel(109, "ability.dmgAtEnd", col2LabelX, y + 5)); - GuiNpcButton dmgEndBtn = new GuiNpcButton(109, col2FieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, teleport.isDamageAtEnd() ? 1 : 0); - dmgEndBtn.setHoverText("ability.hover.dmgAtEnd"); - addButton(dmgEndBtn); - - y += 24; - - // Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - int value = button.getValue(); - switch (id) { - case 100: - teleport.setModeEnum(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; - case 150: - setSubGui(new SubGuiAbilityEffects(teleport.getEffects())); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - teleport.setEffects(result); - } - } - } - - @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; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityTrap.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityTrap.java deleted file mode 100644 index 5c9c52558..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityTrap.java +++ /dev/null @@ -1,126 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityTrap; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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: Duration + Placement - addLabel(new GuiNpcLabel(99, "ability.duration", labelX, y + 5)); - GuiNpcTextField durationField = createIntField(99, fieldX, y, 50, trap.getDurationTicks()); - durationField.setMinMaxDefault(1, 2000, 200); - addTextField(durationField); - - addLabel(new GuiNpcLabel(100, "ability.placement", col2LabelX, y + 5)); - String[] placements = {"Caster", "Target", "Ahead"}; - GuiNpcButton placementBtn = new GuiNpcButton(100, col2FieldX, y, 55, 20, placements, trap.getPlacementEnum().ordinal()); - placementBtn.setHoverText("ability.hover.placement"); - addButton(placementBtn); - - y += 24; - - // Row 2: Trigger Radius - addLabel(new GuiNpcLabel(101, "ability.triggerRad", labelX, y + 5)); - addTextField(createFloatField(101, fieldX, 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: Knockback + Effects button - addLabel(new GuiNpcLabel(108, "ability.knockback", labelX, y + 5)); - addTextField(createFloatField(108, fieldX, y, 50, trap.getKnockback())); - - addButton(new GuiNpcButton(150, col2LabelX, y, 80, 20, "ability.effects")); - } - - @Override - protected void handleTypeButton(int id, GuiNpcButton button) { - if (id == 100) { - trap.setPlacementEnum(AbilityTrap.TrapPlacement.values()[button.getValue()]); - } else if (id == 150) { - setSubGui(new SubGuiAbilityEffects(trap.getEffects())); - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - trap.setEffects(result); - } - } - } - - @Override - protected void handleTypeTextField(int id, GuiNpcTextField field) { - switch (id) { - case 99: - trap.setDurationTicks(field.getInteger()); - break; - 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 108: - trap.setKnockback(parseFloat(field, trap.getKnockback())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityVortex.java b/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityVortex.java deleted file mode 100644 index b56828470..000000000 --- a/src/main/java/noppes/npcs/client/gui/advanced/ability/SubGuiAbilityVortex.java +++ /dev/null @@ -1,129 +0,0 @@ -package noppes.npcs.client.gui.advanced.ability; - -import kamkeel.npcs.controllers.data.ability.AbilityEffect; -import kamkeel.npcs.controllers.data.ability.type.AbilityVortex; -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; -import noppes.npcs.client.gui.util.IAbilityConfigCallback; -import noppes.npcs.client.gui.util.SubGuiInterface; - -import java.util.List; - -/** - * 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)); - GuiNpcButton aoeBtn = new GuiNpcButton(104, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, vortex.isAoe() ? 1 : 0); - aoeBtn.setHoverText("ability.hover.aoe"); - addButton(aoeBtn); - - addLabel(new GuiNpcLabel(105, "ability.maxTargets", col2LabelX, y + 5)); - addTextField(createIntField(105, col2FieldX, y, 50, vortex.getMaxTargets())); - - y += 24; - - // Row 4: Effects button - addButton(new GuiNpcButton(150, labelX, y, 80, 20, "ability.effects")); - - y += 24; - - // Row 5: Damage on Pull + Pull Damage - addLabel(new GuiNpcLabel(108, "ability.dmgOnPull", labelX, y + 5)); - GuiNpcButton dmgOnPullBtn = new GuiNpcButton(108, fieldX, y, 50, 20, new String[]{"gui.no", "gui.yes"}, vortex.isDamageOnPull() ? 1 : 0); - dmgOnPullBtn.setHoverText("ability.hover.dmgOnPull"); - addButton(dmgOnPullBtn); - - 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; - case 150: - setSubGui(new SubGuiAbilityEffects(vortex.getEffects())); - break; - } - } - - @Override - public void subGuiClosed(SubGuiInterface subgui) { - super.subGuiClosed(subgui); - if (subgui instanceof SubGuiAbilityEffects) { - SubGuiAbilityEffects effectsGui = (SubGuiAbilityEffects) subgui; - List result = effectsGui.getResult(); - if (result != null) { - vortex.setEffects(result); - } - } - } - - @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 109: - vortex.setPullDamage(parseFloat(field, vortex.getPullDamage())); - break; - } - } -} diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java new file mode 100644 index 000000000..9263cc880 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -0,0 +1,381 @@ +package noppes.npcs.client.gui.builder; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import noppes.npcs.controllers.AnimationController; +import noppes.npcs.controllers.data.Animation; +import noppes.npcs.client.gui.SubGuiColorSelector; +import noppes.npcs.client.gui.select.GuiAnimationSelection; +import noppes.npcs.client.gui.select.GuiSoundSelection; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.List; +import java.util.function.BooleanSupplier; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Declarative field definition for GUI rendering. + * Built via static factories and chaining methods. + * Client-side only — never instantiate or reference on the server. + */ +@SideOnly(Side.CLIENT) +public class FieldDef { + + private final String label; + private final FieldType type; + private String tab = null; + private Supplier getter; + private Consumer setter; + private BooleanSupplier visibleWhen = () -> true; + private BooleanSupplier enabledWhen = () -> true; + private String hoverText = null; + + // Numeric range + private float min = Float.MIN_VALUE; + private float max = Float.MAX_VALUE; + + // Enum support + private Class> enumClass; + private String[] stringEnumValues; + private Supplier stringEnumGetter; + private Consumer stringEnumSetter; + + // Sub-gui support + private Supplier subGuiFactory; + private Consumer subGuiResultHandler; + + // Button display + private Supplier buttonLabelSupplier; + private Supplier buttonTextColorSupplier; + private Runnable clearAction; + + // Row pairing (ROW type only) + private FieldDef leftChild; + private FieldDef rightChild; + + private FieldDef(String label, FieldType type) { + this.label = label; + this.type = type; + } + + // ═══════════════════════════════════════════════════════════════════ + // STATIC FACTORIES + // ═══════════════════════════════════════════════════════════════════ + + public static FieldDef section(String label) { + return new FieldDef(label, FieldType.SECTION_HEADER); + } + + public static FieldDef floatField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.FLOAT); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept(((Number) v).floatValue()); + return def; + } + + public static FieldDef intField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.INT); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept(((Number) v).intValue()); + return def; + } + + public static FieldDef boolField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.BOOLEAN); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept((Boolean) v); + return def; + } + + @SuppressWarnings("unchecked") + public static > FieldDef enumField(String label, Class enumClass, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.ENUM); + def.enumClass = enumClass; + def.getter = () -> getter.get(); + def.setter = v -> setter.accept((E) v); + return def; + } + + public static FieldDef stringEnumField(String label, String[] values, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.STRING_ENUM); + def.stringEnumValues = values; + def.stringEnumGetter = getter; + def.stringEnumSetter = setter; + return def; + } + + public static FieldDef stringField(String label, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, FieldType.STRING); + def.getter = () -> getter.get(); + def.setter = v -> setter.accept((String) v); + return def; + } + + public static FieldDef labelField(String label, Supplier textSupplier) { + FieldDef def = new FieldDef(label, FieldType.LABEL); + def.getter = () -> textSupplier.get(); + return def; + } + + public static FieldDef subGuiField(String label, Supplier factory, Consumer resultHandler) { + FieldDef def = new FieldDef(label, FieldType.SUB_GUI); + def.subGuiFactory = factory; + def.subGuiResultHandler = resultHandler; + return def; + } + + /** + * Creates a FieldDef with a custom FieldType. Used by extension code + * (e.g. AbilityFieldDefs) to create fields with types like EFFECTS_LIST + * that the base GuiFieldBuilder does not handle. + */ + public static FieldDef custom(String label, FieldType type, Supplier getter, Consumer setter) { + FieldDef def = new FieldDef(label, type); + def.getter = getter; + def.setter = setter; + return def; + } + + /** + * Creates a two-column row pairing two fields side by side. + * If one child is hidden (via visibleWhen), the other renders full-width. + */ + public static FieldDef row(FieldDef left, FieldDef right) { + FieldDef def = new FieldDef("", FieldType.ROW); + def.leftChild = left; + def.rightChild = right; + return def; + } + + // ═══════════════════════════════════════════════════════════════════ + // CONVENIENCE FACTORIES (SUB_GUI wrappers) + // ═══════════════════════════════════════════════════════════════════ + + public static FieldDef colorSubGui(String label, Supplier getter, Consumer setter) { + return subGuiField(label, + () -> new SubGuiColorSelector(getter.get()), + gui -> setter.accept(((SubGuiColorSelector) gui).color & 0x00FFFFFF)) + .buttonLabel(() -> String.format("%06X", getter.get() & 0xFFFFFF)) + .buttonTextColor(() -> getter.get() & 0xFFFFFF); + } + + public static FieldDef soundSubGui(String label, Supplier getter, Consumer setter) { + return subGuiField(label, + () -> new GuiSoundSelection(getter.get()), + gui -> { + GuiSoundSelection s = (GuiSoundSelection) gui; + if (s.selectedResource != null) setter.accept(s.selectedResource.toString()); + }) + .buttonLabel(() -> { + String s = getter.get(); + return s == null || s.isEmpty() ? "gui.none" : s; + }) + .clearable(() -> setter.accept("")); + } + + public static FieldDef animSubGui(String label, + Supplier idGetter, Consumer idSetter, + Supplier nameGetter, Consumer nameSetter) { + return subGuiField(label, + () -> new GuiAnimationSelection(idGetter.get(), nameGetter.get()), + gui -> { + GuiAnimationSelection sel = (GuiAnimationSelection) gui; + if (sel.isBuiltInSelected()) { + nameSetter.accept(sel.selectedBuiltInName); + idSetter.accept(-1); + } else { + idSetter.accept(sel.selectedAnimationId); + nameSetter.accept(""); + } + }) + .buttonLabel(() -> { + String name = nameGetter.get(); + if (name != null && !name.isEmpty()) return name; + int id = idGetter.get(); + if (id >= 0) { + Animation anim = AnimationController.Instance != null + ? (Animation) AnimationController.Instance.get(id) : null; + String animName = anim != null ? anim.getName() : ""; + return animName != null && !animName.isEmpty() + ? "(ID: " + id + ") " + animName : "ID: " + id; + } + return "gui.none"; + }) + .clearable(() -> { idSetter.accept(-1); nameSetter.accept(""); }); + } + + // ═══════════════════════════════════════════════════════════════════ + // CHAINING METHODS + // ═══════════════════════════════════════════════════════════════════ + + public FieldDef tab(String tabName) { + this.tab = tabName; + return this; + } + + public FieldDef range(float min, float max) { + this.min = min; + this.max = max; + return this; + } + + public FieldDef min(float min) { + this.min = min; + return this; + } + + public FieldDef max(float max) { + this.max = max; + return this; + } + + public FieldDef visibleWhen(BooleanSupplier condition) { + this.visibleWhen = condition; + return this; + } + + public FieldDef enabledWhen(BooleanSupplier condition) { + this.enabledWhen = condition; + return this; + } + + public FieldDef hover(String hoverText) { + this.hoverText = hoverText; + return this; + } + + public FieldDef buttonLabel(Supplier supplier) { + this.buttonLabelSupplier = supplier; + return this; + } + + public FieldDef buttonTextColor(Supplier supplier) { + this.buttonTextColorSupplier = supplier; + return this; + } + + public FieldDef clearable(Runnable action) { + this.clearAction = action; + return this; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS + // ═══════════════════════════════════════════════════════════════════ + + public String getLabel() { return label; } + public FieldType getType() { return type; } + public String getTab() { return tab; } + public boolean isVisible() { return visibleWhen.getAsBoolean(); } + public boolean isEnabled() { return enabledWhen.getAsBoolean(); } + public String getHoverText() { return hoverText; } + public float getMin() { return min; } + public float getMax() { return max; } + public boolean hasRange() { return min != Float.MIN_VALUE || max != Float.MAX_VALUE; } + public Class> getEnumClass() { return enumClass; } + public String[] getStringEnumValues() { return stringEnumValues; } + public Supplier getSubGuiFactory() { return subGuiFactory; } + public Consumer getSubGuiResultHandler() { return subGuiResultHandler; } + public boolean hasClearAction() { return clearAction != null; } + public Runnable getClearAction() { return clearAction; } + + public Object getValue() { + return getter != null ? getter.get() : null; + } + + public void setValue(Object value) { + if (setter != null) setter.accept(value); + } + + public String getStringEnumValue() { + return stringEnumGetter != null ? stringEnumGetter.get() : null; + } + + public void setStringEnumValue(String value) { + if (stringEnumSetter != null) stringEnumSetter.accept(value); + } + + public String getButtonLabel() { + if (buttonLabelSupplier != null) return buttonLabelSupplier.get(); + return label; + } + + public Integer getButtonTextColor() { + return buttonTextColorSupplier != null ? buttonTextColorSupplier.get() : null; + } + + public FieldDef getLeftChild() { return leftChild; } + public FieldDef getRightChild() { return rightChild; } + + // ═══════════════════════════════════════════════════════════════════ + // LIST MANIPULATION (for mod injection) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Insert a field before the first field matching the target label. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to insert before + * @param newField The field to insert + * @return true if the target was found and the field was inserted + */ + public static boolean insertBefore(java.util.List fields, String targetLabel, FieldDef newField) { + for (int i = 0; i < fields.size(); i++) { + if (matchesLabel(fields.get(i), targetLabel)) { + fields.add(i, newField); + return true; + } + } + return false; + } + + /** + * Insert a field after the first field matching the target label. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to insert after + * @param newField The field to insert + * @return true if the target was found and the field was inserted + */ + public static boolean insertAfter(List fields, String targetLabel, FieldDef newField) { + for (int i = 0; i < fields.size(); i++) { + if (matchesLabel(fields.get(i), targetLabel)) { + fields.add(i + 1, newField); + return true; + } + } + return false; + } + + /** + * Modify the visibility condition of a field. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to modify + * @param condition The condition to replace + * @return true if the target was found and the condition was modified + */ + public static boolean modifyVisibility(List fields, String targetLabel, BooleanSupplier condition) { + for (FieldDef field : fields) { + if (matchesLabel(field, targetLabel)) { + field.visibleWhen(condition); + return true; + } + } + return false; + } + + private static boolean matchesLabel(FieldDef def, String targetLabel) { + if (targetLabel.equals(def.label)) return true; + if (def.type == FieldType.ROW) { + if (def.leftChild != null && targetLabel.equals(def.leftChild.label)) return true; + if (def.rightChild != null && targetLabel.equals(def.rightChild.label)) return true; + } + return false; + } + +} diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldType.java b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java new file mode 100644 index 000000000..052e2f4cd --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldType.java @@ -0,0 +1,19 @@ +package noppes.npcs.client.gui.builder; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public enum FieldType { + FLOAT, + INT, + BOOLEAN, + ENUM, + STRING_ENUM, + SUB_GUI, + STRING, + SECTION_HEADER, + LABEL, + EFFECTS_LIST, + ROW +} diff --git a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java new file mode 100644 index 000000000..b1f123956 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -0,0 +1,462 @@ +package noppes.npcs.client.gui.builder; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.util.StatCollector; +import noppes.npcs.client.gui.util.GuiNPCInterface; +import noppes.npcs.client.gui.util.GuiNpcButton; +import noppes.npcs.client.gui.util.GuiNpcButtonYesNo; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import noppes.npcs.client.gui.util.GuiScrollWindow; +import noppes.npcs.client.gui.util.SubGuiInterface; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * General-purpose builder that converts a list of {@link FieldDef} into positioned + * GUI widgets inside a {@link GuiScrollWindow}. + *

+ * Uses {@link FieldDef#row(FieldDef, FieldDef)} for two-column layouts. + * Subclasses can override {@link #buildField} to handle custom field types. + */ +@SideOnly(Side.CLIENT) +public class GuiFieldBuilder { + + // Layout defaults (2-column mode) + protected int contentRight = 330; + protected int colLLabel = 5; + protected int colLField = 75; + protected int colLWidth = 70; + protected int colRLabel = 178; + protected int colRField = 248; + protected int colRWidth = 70; + protected int rowHeight = 24; + protected int labelPadding = 8; + + // Dependencies + protected final GuiNPCInterface parent; + protected GuiScrollWindow sw; + protected final FontRenderer fontRenderer; + + // Scroll window ID + protected int scrollWindowId = 0; + + // ID counters + protected int widgetId; + protected int clearId; + protected int labelId; + + // Starting Y + protected int startY = 5; + protected int lastBuildY = 0; + + // Output maps + protected final Map buttonFieldMap = new HashMap<>(); + protected final Map textFieldMap = new HashMap<>(); + protected final Map clearFieldMap = new HashMap<>(); + + public GuiFieldBuilder(GuiNPCInterface parent, FontRenderer fontRenderer) { + this.parent = parent; + this.fontRenderer = fontRenderer; + } + + // ═══════════════════════════════════════════════════════════════════ + // CONFIG CHAINING + // ═══════════════════════════════════════════════════════════════════ + + public GuiFieldBuilder scrollWindowId(int id) { this.scrollWindowId = id; return this; } + public GuiFieldBuilder contentRight(int v) { this.contentRight = v; return this; } + public GuiFieldBuilder startIds(int widget, int clear, int label) { + this.widgetId = widget; this.clearId = clear; this.labelId = label; return this; + } + public GuiFieldBuilder startY(int y) { this.startY = y; return this; } + public GuiFieldBuilder rowHeight(int h) { this.rowHeight = h; return this; } + + // ═══════════════════════════════════════════════════════════════════ + // BUILD + // ═══════════════════════════════════════════════════════════════════ + + /** + * Creates a {@link GuiScrollWindow} at the given position/size, builds all fields into it, + * and sets maxScrollY automatically. The returned window is ready to use. + */ + public GuiScrollWindow buildScrollWindow(List fields, int x, int y, int width, int height) { + this.sw = new GuiScrollWindow(parent, x, y, width, height, 0); + sw.backgroundColor = 0x88000000; + // Register with parent first — this calls initGui() which clears widget lists, + // so we must add widgets AFTER this point + parent.addScrollableGui(scrollWindowId, sw); + int finalY = build(fields); + sw.maxScrollY = Math.max(finalY - height, 0); + return sw; + } + + /** + * Processes all fields and adds widgets to the scroll window. + * @return the final Y position after all fields + */ + protected int build(List fields) { + buttonFieldMap.clear(); + textFieldMap.clear(); + clearFieldMap.clear(); + + int y = startY; + + for (int i = 0; i < fields.size(); i++) { + FieldDef def = fields.get(i); + + // Let subclasses handle custom types; returns -1 if not handled + int customResult = buildField(def, y, fields, i); + if (customResult >= 0) { + // Subclass handled it, check if index was advanced + int newIndex = getLastHandledIndex(); + if (newIndex > i) i = newIndex; + y = customResult; + continue; + } + + // Skip invisible fields + if (!def.isVisible()) continue; + + // Section header + if (def.getType() == FieldType.SECTION_HEADER) { + y += 3; + GuiNpcLabel sectionLabel = new GuiNpcLabel(labelId++, def.getLabel(), colLLabel, y + 2, 0xFFFF55); + if (def.getHoverText() != null && !def.getHoverText().isEmpty()) { + sectionLabel.setHoverText(def.getHoverText()); + } + sw.addLabel(sectionLabel); + y += 15; + continue; + } + + // ROW: explicit two-column pair + if (def.getType() == FieldType.ROW) { + FieldDef left = def.getLeftChild(); + FieldDef right = def.getRightChild(); + boolean leftVis = left != null && left.isVisible(); + boolean rightVis = right != null && right.isVisible(); + + if (leftVis && rightVis) { + renderFieldAt(left, colLLabel, colLField, colLWidth, y); + renderFieldAt(right, colRLabel, colRField, colRWidth, y); + } else if (leftVis) { + renderFullWidth(left, y); + } else if (rightVis) { + renderFullWidth(right, y); + } + if (leftVis || rightVis) y += rowHeight; + continue; + } + + // Full-width field + renderFullWidth(def, y); + y += rowHeight; + } + + lastBuildY = y; + return y; + } + + /** + * Hook for subclasses to handle custom field types (e.g. EFFECTS_LIST). + * Return the new Y position if handled, or -1 if not handled (base class will process it). + * If handling advances the field index, call {@link #setLastHandledIndex(int)}. + */ + protected int buildField(FieldDef def, int y, List fields, int index) { + return -1; + } + + private int lastHandledIndex = -1; + protected void setLastHandledIndex(int index) { this.lastHandledIndex = index; } + protected int getLastHandledIndex() { return lastHandledIndex; } + + // ═══════════════════════════════════════════════════════════════════ + // FIELD RENDERING + // ═══════════════════════════════════════════════════════════════════ + + @SuppressWarnings({"unchecked", "rawtypes"}) + protected void renderFieldAt(FieldDef def, int labelX, int fieldX, int fieldW, int y) { + GuiNpcLabel fieldLabel = new GuiNpcLabel(labelId++, def.getLabel(), labelX, y + 5, 0xFFFFFF); + String hover = def.getHoverText(); + if (hover != null && !hover.isEmpty()) { + fieldLabel.setHoverText(hover); + } + sw.addLabel(fieldLabel); + + switch (def.getType()) { + case FLOAT: { + float fVal = def.getValue() instanceof Number ? ((Number) def.getValue()).floatValue() : 0f; + GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, String.valueOf(fVal)); + tf.setFloatsOnly(); + if (def.hasRange()) tf.setMinMaxDefaultFloat(def.getMin(), def.getMax(), fVal); + if (!def.isEnabled()) tf.setEnabled(false); + if (hover != null) tf.setHoverText(hover); + sw.addTextField(tf); + textFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + case INT: { + int iVal = def.getValue() instanceof Number ? ((Number) def.getValue()).intValue() : 0; + GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, String.valueOf(iVal)); + tf.setIntegersOnly(); + if (def.hasRange()) tf.setMinMaxDefault((int) def.getMin(), (int) def.getMax(), iVal); + if (!def.isEnabled()) tf.setEnabled(false); + if (hover != null) tf.setHoverText(hover); + sw.addTextField(tf); + textFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + case STRING: { + String sVal = def.getValue() != null ? def.getValue().toString() : ""; + GuiNpcTextField tf = new GuiNpcTextField(widgetId, parent, fontRenderer, fieldX, y, fieldW, 20, sVal); + if (!def.isEnabled()) tf.setEnabled(false); + if (hover != null) tf.setHoverText(hover); + sw.addTextField(tf); + textFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + case LABEL: { + String text = def.getValue() != null ? def.getValue().toString() : ""; + sw.addLabel(new GuiNpcLabel(labelId++, text, fieldX, y + 5, 0xAAAAAA)); + widgetId++; + clearId++; + break; + } + case BOOLEAN: { + boolean bVal = def.getValue() instanceof Boolean ? (Boolean) def.getValue() : false; + GuiNpcButtonYesNo btn = new GuiNpcButtonYesNo(widgetId, fieldX, y, fieldW, 20, bVal); + if (!def.isEnabled()) btn.setEnabled(false); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + case ENUM: { + Class> enumClass = def.getEnumClass(); + if (enumClass != null) { + Enum[] constants = enumClass.getEnumConstants(); + String[] names = new String[constants.length]; + for (int i = 0; i < constants.length; i++) names[i] = constants[i].toString(); + int selected = def.getValue() instanceof Enum ? ((Enum) def.getValue()).ordinal() : 0; + GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, fieldW, 20, names, selected); + if (!def.isEnabled()) btn.setEnabled(false); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + } + widgetId++; + clearId++; + break; + } + case STRING_ENUM: { + String[] values = def.getStringEnumValues(); + if (values != null && values.length > 0) { + String curVal = def.getStringEnumValue(); + int selected = 0; + for (int i = 0; i < values.length; i++) { + if (values[i].equals(curVal)) { selected = i; break; } + } + GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, fieldW, 20, values, selected); + if (!def.isEnabled()) btn.setEnabled(false); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + } + widgetId++; + clearId++; + break; + } + case SUB_GUI: { + String btnText = def.getButtonLabel(); + int btnW; + if (def.hasClearAction()) { + btnW = contentRight - 22 - fieldX; + GuiNpcButton clearBtn = new GuiNpcButton(clearId, contentRight - 20, y, 20, 20, "X"); + sw.addButton(clearBtn); + clearFieldMap.put(clearId, def); + } else { + btnW = contentRight - fieldX; + } + GuiNpcButton btn = new GuiNpcButton(widgetId, fieldX, y, btnW, 20, btnText); + Integer textColor = def.getButtonTextColor(); + if (textColor != null) btn.setTextColor(textColor); + if (!def.isEnabled()) btn.setEnabled(false); + if (hover != null) btn.setHoverText(hover); + sw.addButton(btn); + buttonFieldMap.put(widgetId, def); + widgetId++; + clearId++; + break; + } + default: + // Unknown type — skip, incrementing IDs to stay in sync + widgetId++; + clearId++; + break; + } + } + + private void renderFullWidth(FieldDef def, int y) { + int fieldW = getFullFieldWidth(def); + String translated = StatCollector.translateToLocal(def.getLabel()); + int labelW = fontRenderer.getStringWidth(translated); + int fieldX = colLLabel + labelW + labelPadding; + renderFieldAt(def, colLLabel, fieldX, fieldW, y); + } + + protected int getFullFieldWidth(FieldDef def) { + switch (def.getType()) { + case FLOAT: + case INT: return 60; + case STRING: return 200; + case BOOLEAN: return 50; + case LABEL: return 60; + case ENUM: + case STRING_ENUM: return 120; + case SUB_GUI: return def.hasClearAction() ? 175 : 200; + default: return 80; + } + } + + // ═══════════════════════════════════════════════════════════════════ + // EVENT HANDLING + // ═══════════════════════════════════════════════════════════════════ + + /** + * Handles button events for declarative fields. + * Call from parent GUI's buttonEvent(). Returns true if the event was handled. + *

+ * For SUB_GUI fields, the sub-gui is opened directly via {@code parent.setSubGuiWithResult()}, + * so the result handler survives initGui() rebuilds. After this returns true, check + * {@code parent.hasSubGui()} to determine if initGui() should be called. + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + public boolean handleButtonEvent(int buttonId, GuiButton button) { + // Check clear buttons first + if (clearFieldMap.containsKey(buttonId)) { + FieldDef def = clearFieldMap.get(buttonId); + if (def != null && def.hasClearAction()) { + def.getClearAction().run(); + return true; + } + } + + // Check field buttons + FieldDef def = buttonFieldMap.get(buttonId); + if (def == null) return false; + + switch (def.getType()) { + case BOOLEAN: + def.setValue(((GuiNpcButton) button).getValue() == 1); + return true; + case ENUM: { + int idx = ((GuiNpcButton) button).getValue(); + Class> ec = def.getEnumClass(); + if (ec != null) { + Enum[] constants = ec.getEnumConstants(); + if (idx >= 0 && idx < constants.length) def.setValue(constants[idx]); + } + return true; + } + case STRING_ENUM: { + int idx = ((GuiNpcButton) button).getValue(); + String[] values = def.getStringEnumValues(); + if (values != null && idx >= 0 && idx < values.length) def.setStringEnumValue(values[idx]); + return true; + } + case SUB_GUI: + if (def.getSubGuiFactory() != null) { + parent.setSubGuiWithResult(def.getSubGuiFactory().get(), sub -> { + if (def.getSubGuiResultHandler() != null) { + def.getSubGuiResultHandler().accept(sub); + } + }); + } + return true; + default: + return false; + } + } + + /** + * Handles text field unfocus events for declarative fields. + * Call from parent GUI's unFocused(). Returns true if the value actually changed. + */ + public boolean handleTextFieldEvent(int textFieldId, GuiNpcTextField field) { + FieldDef def = textFieldMap.get(textFieldId); + if (def == null) return false; + + switch (def.getType()) { + case FLOAT: + try { + float newVal = Float.parseFloat(field.getText()); + Object old = def.getValue(); + float oldVal = old instanceof Number ? ((Number) old).floatValue() : 0f; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) {} + return false; + case INT: + try { + int newVal = Integer.parseInt(field.getText()); + Object old = def.getValue(); + int oldVal = old instanceof Number ? ((Number) old).intValue() : 0; + if (newVal != oldVal) { + def.setValue(newVal); + return true; + } + } catch (NumberFormatException ignored) {} + return false; + case STRING: + String newVal = field.getText(); + Object old = def.getValue(); + String oldVal = old != null ? old.toString() : ""; + if (!newVal.equals(oldVal)) { + def.setValue(newVal); + return true; + } + return false; + default: + return false; + } + } + + /** + * Handles sub-gui close events. Call from parent GUI's subGuiClosed(). + *

+ * Note: SUB_GUI fields opened via handleButtonEvent use + * {@code parent.setSubGuiWithResult()}, so their results are handled + * automatically by {@code GuiNPCInterface.closeSubGui()}. This method + * only handles sub-guis opened through other means. + */ + public boolean handleSubGuiClosed(SubGuiInterface subgui) { + return false; + } + + // ═══════════════════════════════════════════════════════════════════ + // GETTERS + // ═══════════════════════════════════════════════════════════════════ + + public Map getButtonFieldMap() { return buttonFieldMap; } + public Map getTextFieldMap() { return textFieldMap; } + public Map getClearFieldMap() { return clearFieldMap; } + public GuiScrollWindow getScrollWindow() { return sw; } + public int getLastBuildY() { return lastBuildY; } + public int getNextLabelId() { return labelId; } +} diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java index 0141e931a..3ac3923b4 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageAnimations.java @@ -51,8 +51,8 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol // Track if current animation is built-in private boolean currentIsBuiltIn = false; - public GuiNPCManageAnimations(EntityNPCInterface npc, boolean save) { - super(npc); + public GuiNPCManageAnimations(EntityNPCInterface npc, boolean save, boolean hasMenuNpc) { + super(npc, hasMenuNpc); this.setSave(save); this.xOffset = -148 + 70; this.yOffset = -170 + 137; @@ -65,16 +65,17 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol public void initGui() { super.initGui(); + // Toggle button - added FIRST to maintain stable buttonList index + // (prevents double-toggle when initGui() is called from actionPerformed) + String toggleLabel = showingBuiltIn ? "gui.builtin" : "gui.custom"; + this.addButton(new GuiNpcButton(10, guiLeft + 368, guiTop + 56, 45, 20, toggleLabel)); + // 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); scrollAnimations.setSize(143, 185); @@ -200,11 +201,15 @@ public class GuiNPCManageAnimations extends GuiModelInterface2 implements IScrol // Toggle button if (button.id == 10) { showingBuiltIn = !showingBuiltIn; - // Clear selection when switching views + // Clear selection and search when switching views selected = null; + search = ""; animation = new Animation(); currentIsBuiltIn = false; + playingAnimation = false; scrollAnimations.clear(); + // Re-request data to ensure both lists are populated + PacketClient.sendClient(new AnimationsGetPacket()); initGui(); return; } diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java index 246e528f3..59adbdd91 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNPCManageFactions.java @@ -85,11 +85,13 @@ public class GuiNPCManageFactions extends GuiNPCInterface2 implements IScrollDat addLabel(new GuiNpcLabel(3, "faction.hidden", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(3, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.hideFaction ? 1 : 0)); + getButton(3).setHoverText("faction.hidden.hover"); y += 23; addLabel(new GuiNpcLabel(4, "faction.attacked", guiLeft + 8, y + 5)); this.addButton(new GuiNpcButton(4, guiLeft + 100, y, 45, 20, new String[]{"gui.no", "gui.yes"}, faction.getsAttacked ? 1 : 0)); + getButton(4).setHoverText("faction.attacked.hover"); y += 23; diff --git a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java index 8fa2e4e41..b06f9d097 100644 --- a/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java +++ b/src/main/java/noppes/npcs/client/gui/global/GuiNpcManageAbilities.java @@ -3,6 +3,7 @@ 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 java.util.UUID; import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.request.ability.CustomAbilitiesGetPacket; @@ -15,6 +16,11 @@ import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.StatCollector; import noppes.npcs.client.NoppesUtil; +import kamkeel.npcs.controllers.data.ability.AbilityVariant; +import noppes.npcs.client.gui.advanced.SubGuiAbilityConfig; +import noppes.npcs.client.gui.advanced.SubGuiAbilityTypeSelect; +import noppes.npcs.client.gui.advanced.SubGuiAbilityVariantSelect; +import noppes.npcs.client.gui.advanced.SubGuiDuplicateNameConfirm; import noppes.npcs.client.gui.util.AbilityPreviewExecutor; import noppes.npcs.client.gui.util.GuiAbilityInterface; import noppes.npcs.client.gui.util.GuiCustomScroll; @@ -60,12 +66,19 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface private String search = ""; private Ability selectedAbility = null; + // ==================== PENDING SAVE ==================== + private Ability pendingSaveAbility = null; + private boolean pendingNewCreation = false; + + // ==================== PENDING VARIANT ==================== + private String pendingTypeId = null; + // ==================== PREVIEW ==================== private AbilityPreviewExecutor previewExecutor; private long prevTick = 0; - public GuiNpcManageAbilities(EntityNPCInterface npc) { - super(npc); + public GuiNpcManageAbilities(EntityNPCInterface npc, boolean hasMenuNpc) { + super(npc, hasMenuNpc); // Layout offset this.xOffset = -148 + 110; @@ -87,14 +100,17 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface public void initGui() { super.initGui(); - // 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); + // Add button + addButton(new GuiNpcButton(2, guiLeft + 368, guiTop + 8, 45, 20, "gui.add")); // Remove button addButton(new GuiNpcButton(1, guiLeft + 368, guiTop + 30, 45, 20, "gui.remove")); getButton(1).setEnabled(selected != null && !selected.isEmpty() && displayToUuid.containsKey(selected)); + // Edit button + addButton(new GuiNpcButton(100, guiLeft + 368, guiTop + 52, 45, 20, "gui.edit")); + getButton(100).setEnabled(selected != null && !selected.isEmpty() && selectedAbility != null); + // Scroll list of saved abilities (right side) if (scroll == null) { scroll = new GuiCustomScroll(this, 0); @@ -211,7 +227,10 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface int id = guibutton.id; - if (id == 1 && selected != null && selectedUuid != null) { + if (id == 2) { + // Add — open type selection + setSubGui(new SubGuiAbilityTypeSelect()); + } else 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) { @@ -329,9 +348,112 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void subGuiClosed(SubGuiInterface subgui) { + if (subgui instanceof SubGuiAbilityVariantSelect) { + SubGuiAbilityVariantSelect variantGui = (SubGuiAbilityVariantSelect) subgui; + int idx = variantGui.getSelectedIndex(); + if (idx >= 0 && pendingTypeId != null) { + Ability newAbility = AbilityController.Instance.create(pendingTypeId); + if (newAbility != null) { + variantGui.getVariants().get(idx).apply(newAbility); + newAbility.setId(UUID.randomUUID().toString()); + if (hasDuplicateName(newAbility)) { + pendingSaveAbility = newAbility; + pendingNewCreation = true; + pendingTypeId = null; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + pendingTypeId = null; + saveAndOpenConfig(newAbility); + return; + } + } + pendingTypeId = null; + } else if (subgui instanceof SubGuiAbilityTypeSelect) { + String typeId = ((SubGuiAbilityTypeSelect) subgui).getSelectedTypeId(); + if (typeId != null) { + java.util.List variants = AbilityController.Instance.getVariantsForType(typeId); + if (variants.size() > 1) { + pendingTypeId = typeId; + setSubGui(new SubGuiAbilityVariantSelect(variants)); + return; + } + Ability newAbility = AbilityController.Instance.create(typeId); + if (newAbility != null) { + if (variants.size() == 1) { + variants.get(0).apply(newAbility); + } + newAbility.setId(UUID.randomUUID().toString()); + if (hasDuplicateName(newAbility)) { + pendingSaveAbility = newAbility; + pendingNewCreation = true; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + saveAndOpenConfig(newAbility); + return; + } + } + } else if (subgui instanceof SubGuiDuplicateNameConfirm) { + SubGuiDuplicateNameConfirm confirm = (SubGuiDuplicateNameConfirm) subgui; + if (confirm.isConfirmed() && pendingSaveAbility != null) { + if (pendingNewCreation) { + saveAndOpenConfig(pendingSaveAbility); + pendingSaveAbility = null; + pendingNewCreation = false; + return; + } else { + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + pendingSaveAbility = null; + } + } else if (pendingSaveAbility != null) { + if (pendingNewCreation) { + // Cancel new creation - discard + pendingSaveAbility = null; + pendingNewCreation = false; + } else { + // Cancel edit save - re-open config GUI to change name + Ability ability = pendingSaveAbility; + pendingSaveAbility = null; + setSubGui(ability.createConfigGui(this)); + return; + } + } + } else if (pendingSaveAbility != null) { + // Config GUI closed with a pending save (set by onAbilitySaved) + if (hasDuplicateName(pendingSaveAbility)) { + pendingNewCreation = false; + setSubGui(new SubGuiDuplicateNameConfirm()); + return; + } + PacketClient.sendClient(new CustomAbilitySavePacket(pendingSaveAbility.writeNBT())); + PacketClient.sendClient(new CustomAbilitiesGetPacket()); + pendingSaveAbility = null; + } initGui(); } + private void saveAndOpenConfig(Ability ability) { + PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + selectedAbility = ability; + selected = ability.getName(); + selectedUuid = ability.getId(); + previewExecutor.stop(); + setSubGui(ability.createConfigGui(this)); + } + + private boolean hasDuplicateName(Ability ability) { + String name = ability.getName(); + if (name == null || name.isEmpty()) return false; + for (java.util.Map.Entry entry : displayToUuid.entrySet()) { + if (entry.getKey().equals(name) && !entry.getValue().equals(ability.getId())) { + return true; + } + } + return false; + } + @Override public void confirmClicked(boolean result, int id) { NoppesUtil.openGUI(player, this); @@ -349,7 +471,8 @@ public class GuiNpcManageAbilities extends GuiAbilityInterface @Override public void onAbilitySaved(Ability ability) { - PacketClient.sendClient(new CustomAbilitySavePacket(ability.writeNBT())); + // Defer save until subGuiClosed where we can check for duplicate names + pendingSaveAbility = ability; } @Override diff --git a/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java b/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java index a50622529..11ffa198d 100644 --- a/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java +++ b/src/main/java/noppes/npcs/client/gui/player/AuctionTooltipHandler.java @@ -4,14 +4,18 @@ 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.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; +import net.minecraftforge.event.entity.player.ItemTooltipEvent; 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.containers.SlotAuctionDisplay; import noppes.npcs.controllers.data.AuctionClaim; import noppes.npcs.controllers.data.AuctionListing; @@ -19,45 +23,60 @@ import java.util.List; /** * Handles adding auction information to item tooltips when viewing auction GUIs. - * Called from MixinItem when Item.addInformation is invoked. + * Called from ItemTooltipEvent in ClientEventHandler. + * + * Uses slot-based lookup (slot index) instead of ItemStack comparison to correctly + * handle duplicate items with different auction data (e.g., two porkchops at different prices). */ @SideOnly(Side.CLIENT) public class AuctionTooltipHandler { /** - * Add auction information to an item's tooltip if we're in an auction GUI. + * Handle ItemTooltipEvent - append auction info to the end of the tooltip. */ - public static void addAuctionInfo(ItemStack stack, List tooltip) { - if (stack == null || tooltip == null) return; + public static void onItemTooltip(ItemTooltipEvent event) { + if (event.itemStack == 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); + addListingTooltip((GuiAuctionListing) screen, event.itemStack, event.toolTip); + } else if (screen instanceof GuiAuctionTrades) { + addTradesTooltip((GuiAuctionTrades) screen, event.itemStack, event.toolTip); + } else if (screen instanceof GuiAuctionSell) { + addSellTooltip((GuiAuctionSell) screen, event.itemStack, event.toolTip); } } /** - * Add auction info when viewing the main listings page. + * Find the slot in the container whose getStack() returns the exact same ItemStack reference. + * This avoids the duplicate item bug where ItemStack.areItemStacksEqual matches the wrong listing. */ + private static Slot findHoveredSlot(GuiContainer gui, ItemStack stack) { + if (stack == null) return null; + for (Object obj : gui.inventorySlots.inventorySlots) { + Slot slot = (Slot) obj; + if (slot.getHasStack() && slot.getStack() == stack) { + return slot; + } + } + return null; + } + + // ========== Listing Page ========== + private static void addListingTooltip(GuiAuctionListing gui, ItemStack stack, List tooltip) { - ContainerAuctionListing container = (ContainerAuctionListing) gui.inventorySlots; + Slot slot = findHoveredSlot(gui, stack); + if (slot == null || !(slot instanceof SlotAuctionDisplay)) return; + + ContainerAuctionListing container = gui.getListingContainer(); if (container == null) return; - // Find the listing that matches this ItemStack - AuctionListing listing = container.getListingForItem(stack); + int displayIndex = slot.getSlotIndex(); + AuctionListing listing = container.getListingAt(displayIndex); if (listing == null) return; tooltip.add(""); @@ -90,149 +109,153 @@ public class AuctionTooltipHandler { tooltip.add((timeRemaining < 3600000 ? EnumChatFormatting.RED : EnumChatFormatting.WHITE) + timeText); } - /** - * Add auction info when viewing the trades page. - */ + // ========== Trades Page ========== + private static void addTradesTooltip(GuiAuctionTrades gui, ItemStack stack, List tooltip) { - ContainerAuctionTrades container = (ContainerAuctionTrades) gui.inventorySlots; + Slot slot = findHoveredSlot(gui, stack); + if (slot == null || !(slot instanceof SlotAuctionDisplay)) return; + + ContainerAuctionTrades container = gui.getTradesContainer(); 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")); + int displayIndex = slot.getSlotIndex(); - 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")); + // Check listings first (selling or bidding) + AuctionListing listing = container.getListingAt(displayIndex); + if (listing != null) { + if (container.isSellingAt(displayIndex)) { + addSellingTooltip(listing, tooltip); + } else if (container.isBiddingAt(displayIndex)) { + addBiddingTooltip(listing, tooltip); } - - 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); + // Check claims + AuctionClaim claim = container.getClaimAt(displayIndex); 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")); - } + addClaimTooltip(claim, tooltip); } } - /** - * Add sell page tooltip info. - */ + private static void addSellingTooltip(AuctionListing listing, List tooltip) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.selling")); + + 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.GRAY + StatCollector.translateToLocal("auction.noBids")); + } + + long timeRemaining = listing.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")); + } + + private static void addBiddingTooltip(AuctionListing listing, List tooltip) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.trades.bidding")); + + 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)); + + long timeRemaining = listing.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")); + } + + private static void addClaimTooltip(AuctionClaim claim, List tooltip) { + tooltip.add(""); + + switch (claim.type) { + case ITEM: + if (claim.isReturned) { + tooltip.add(EnumChatFormatting.RED + StatCollector.translateToLocal("auction.trades.expired")); + } else { + tooltip.add(EnumChatFormatting.GREEN + StatCollector.translateToLocal("auction.trades.won")); + } + break; + case CURRENCY: + 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: + 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 + 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(""); + + // Rebid option for REFUND claims with item + 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")); + } + } + + // ========== Sell Page ========== + private static void addSellTooltip(GuiAuctionSell gui, ItemStack stack, List tooltip) { + Slot slot = findHoveredSlot(gui, stack); + if (slot == null) return; + 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 + if (container.isSellSlot(slot.slotNumber)) { tooltip.add(""); tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.leftClear")); tooltip.add(EnumChatFormatting.YELLOW + StatCollector.translateToLocal("auction.sell.rightRemove")); - return; + } else if (container.isPlayerInventorySlot(slot.slotNumber)) { + tooltip.add(""); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.leftAdd")); + tooltip.add(EnumChatFormatting.GRAY + StatCollector.translateToLocal("auction.sell.rightAddOne")); } - - // 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. - */ + // ========== Formatting Utilities ========== + private static String formatCurrency(long amount) { if (amount < 1000) { return amount + " " + AuctionClientConfig.getCurrencyName(); @@ -250,9 +273,6 @@ public class AuctionTooltipHandler { return sb.toString() + " " + AuctionClientConfig.getCurrencyName(); } - /** - * Format time remaining. - */ private static String formatTimeRemaining(long milliseconds) { if (milliseconds <= 0) { return StatCollector.translateToLocal("auction.ended"); diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java index 7efdbe9c9..c34223550 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionInterface.java @@ -112,16 +112,16 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { mc.renderEngine.bindTexture(AUCTION_BACKGROUND); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + drawAuctionContent(partialTicks, mouseX, mouseY); + 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); } @@ -167,12 +167,12 @@ public abstract class GuiAuctionInterface extends GuiContainerNPCInterface { 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); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } /** Draw dark overlay for unavailable slots */ protected void drawDarkenedOverlay(int x, int y) { - drawColoredOverlay(x, y, 0x80000000); + drawColoredOverlay(x, y, 0xC0000000); } /** Draw icon texture on slot (16x16) */ diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java index 21b0f6f01..f52d5fa63 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiAuctionTrades.java @@ -38,10 +38,10 @@ public class GuiAuctionTrades extends GuiAuctionInterface implements IGuiData { 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 static final int TINT_BLUE = 0x605080FF; // Active listing/bid (selling) + private static final int TINT_GREEN = 0x6050FF50; // Sold (currency claim) or Won (item claim) + private static final int TINT_YELLOW = 0x60FFFF50; // Outbid (refund claim) + private static final int TINT_RED = 0x60FF5050; // Expired/Returned (item returned to seller) private final ContainerAuctionTrades tradesContainer; private int maxTradeSlots; diff --git a/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java b/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java index b0a1c6c32..55f88ac8c 100644 --- a/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java +++ b/src/main/java/noppes/npcs/client/gui/player/GuiNPCTrader.java @@ -3,6 +3,7 @@ package noppes.npcs.client.gui.player; import kamkeel.npcs.network.PacketClient; import kamkeel.npcs.network.packets.player.GetTraderData; import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; @@ -332,6 +333,22 @@ public class GuiNPCTrader extends GuiContainerNPCInterface implements IGuiData { return sb.toString(); } + @Override + protected void handleMouseClick(Slot slot, int slotId, int mouseButton, int modifier) { + // Client-side balance prediction: immediately subtract currency cost on click + // so the displayed balance updates instantly without waiting for server response. + if (slotId >= 0 && slotId < 18 && mouseButton == 0) { + long cost = currencyCost[slotId]; + if (cost > 0 && playerBalance >= cost) { + ItemStack sold = role.inventorySold.items.get(slotId); + if (sold != null && container.canBuy(slotId, player)) { + playerBalance -= cost; + } + } + } + super.handleMouseClick(slot, slotId, mouseButton, modifier); + } + @Override public void save() { } diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java index 2a1f04344..7161722d5 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiAnimationSelection.java @@ -55,7 +55,6 @@ public class GuiAnimationSelection extends SubGuiInterface implements ICustomScr * Constructor for selecting by name (built-in) or ID (user). */ public GuiAnimationSelection(int animationId, String animationName) { - drawDefaultBackground = false; title = ""; setBackground("menubg.png"); xSize = 220; diff --git a/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java b/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java index 341b3cc48..aae3043ce 100644 --- a/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java +++ b/src/main/java/noppes/npcs/client/gui/select/GuiSoundSelection.java @@ -39,7 +39,6 @@ public class GuiSoundSelection extends SubGuiInterface implements ICustomScrollL public static HashMap> cachedDomains = new HashMap<>(); public GuiSoundSelection(String sound) { - drawDefaultBackground = false; title = ""; setBackground("menubg.png"); xSize = 366; diff --git a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java index 3dce761d5..7d856d916 100644 --- a/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java +++ b/src/main/java/noppes/npcs/client/gui/util/AbilityPreviewExecutor.java @@ -4,15 +4,10 @@ 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.ability.PreviewEntityHandler; 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; @@ -25,38 +20,39 @@ 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 + * Uses unified execution: calls the REAL ability methods (onWindUpTick, onExecute, onActiveTick) + * with previewMode=true. Abilities skip damage/effects/sounds when isPreview() returns true. * - * 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) + * Lifecycle: + * 1. WINDUP phase - real onWindUpTick() called, telegraph shown, entities may spawn + * 2. ACTIVE phase - real onExecute() then onActiveTick() called, physics simulated + * 3. EXTENDED phase - 100 extra ticks to observe results (entities continue updating) + * 4. IDLE - preview complete */ @SideOnly(Side.CLIENT) -public class AbilityPreviewExecutor { +public class AbilityPreviewExecutor implements PreviewEntityHandler { // ==================== PREVIEW STATE ==================== private Ability previewAbility; private EntityNPCInterface previewNpc; - private AbilityPhase phase = AbilityPhase.IDLE; + + /** Executor's own phase tracking (separate from ability.getPhase()) */ + private enum ExecutorPhase { IDLE, WINDUP, ACTIVE, EXTENDED } + private ExecutorPhase executorPhase = ExecutorPhase.IDLE; + private int currentTick = 0; private boolean playing = false; private boolean paused = false; // ==================== TIMING ==================== private static final int EXTENDED_DURATION = 100; - private int activeDuration = 40; + private int maxPreviewDuration = 200; // ==================== 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 ==================== @@ -74,63 +70,69 @@ public class AbilityPreviewExecutor { } /** - * Start previewing an ability. + * Start previewing an ability using unified execution. + * Sets previewMode=true on the ability, then calls its real methods. */ 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(); + this.maxPreviewDuration = ability.getMaxPreviewDuration(); // Save NPC start position for restoring later this.npcStartX = npc.posX; this.npcStartY = npc.posY; this.npcStartZ = npc.posZ; + // Enable preview mode on the ability + ability.setPreviewMode(true); + ability.setPreviewEntityHandler(this); + // 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); + // Use the ability's real start() method with the fake target + ability.start(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; - } + if (ability.getWindUpTicks() <= 0) { + // No windup — go straight to active + this.executorPhase = ExecutorPhase.ACTIVE; + transitionToActive(); + } else { + // Normal windup flow + this.executorPhase = ExecutorPhase.WINDUP; - // Spawn preview entity on first tick if ability spawns during windup - if (ability.spawnPreviewDuringWindup()) { - spawnPreviewEntity(); + // 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; + } } } /** * 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; @@ -145,15 +147,12 @@ public class AbilityPreviewExecutor { } } - /** - * 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) { + if (previewAbility == null || executorPhase == ExecutorPhase.IDLE) { return; } playing = true; @@ -170,6 +169,9 @@ public class AbilityPreviewExecutor { public void pause() { paused = true; + // Immediately sync prevPos to pos for NPC and all entities to prevent interpolation jitter + syncPrevPositions(); + if (previewNpc != null) { AnimationData data = previewNpc.display.animationData; if (data.animation != null) { @@ -178,10 +180,37 @@ public class AbilityPreviewExecutor { } } + /** + * Sync prevPos to pos for the NPC and all preview entities. + * Prevents rendering interpolation jitter when standing still or paused. + */ + private void syncPrevPositions() { + if (previewNpc != null) { + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + } + for (Entity entity : previewEntities) { + if (entity != null && !entity.isDead) { + entity.prevPosX = entity.posX; + entity.prevPosY = entity.posY; + entity.prevPosZ = entity.posZ; + } + } + } + public void stop() { + // Clean up the ability + if (previewAbility != null) { + previewAbility.cleanup(); + previewAbility.setPreviewMode(false); + previewAbility.setPreviewEntityHandler(null); + previewAbility.reset(); + } + playing = false; paused = false; - phase = AbilityPhase.IDLE; + executorPhase = ExecutorPhase.IDLE; currentTick = 0; previewTelegraph = null; @@ -203,9 +232,11 @@ public class AbilityPreviewExecutor { previewNpc.prevPosX = npcStartX; previewNpc.prevPosY = npcStartY; previewNpc.prevPosZ = npcStartZ; + previewNpc.motionX = 0; + previewNpc.motionY = 0; + previewNpc.motionZ = 0; } - // Remove fake target fakeTarget = null; if (previewNpc != null) { @@ -216,13 +247,24 @@ public class AbilityPreviewExecutor { } /** - * Tick the preview forward. + * Tick the preview forward. Calls real ability methods. */ public void tick() { - if (!playing || paused || previewAbility == null || previewNpc == null) { + if (!playing || previewAbility == null || previewNpc == null) { return; } + if (paused) { + // Sync prevPos to pos for NPC and all entities to prevent interpolation jitter while paused + syncPrevPositions(); + return; + } + + // Sync NPC's prevPos to current pos BEFORE any updates to prevent jitter when standing still + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + currentTick++; if (previewTelegraph != null) { @@ -231,14 +273,14 @@ public class AbilityPreviewExecutor { tickEntities(); - switch (phase) { + switch (executorPhase) { case WINDUP: tickWindup(); break; case ACTIVE: tickActive(); break; - case IDLE: + case EXTENDED: tickExtended(); break; default: @@ -247,7 +289,8 @@ public class AbilityPreviewExecutor { } private void tickWindup() { - previewAbility.onPreviewWindUpTick(previewNpc, currentTick); + // Call the REAL windup tick method + previewAbility.onWindUpTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); if (currentTick >= previewAbility.getWindUpTicks()) { transitionToActive(); @@ -255,35 +298,41 @@ public class AbilityPreviewExecutor { } private void tickActive() { - previewAbility.onPreviewActiveTick(previewNpc, currentTick); + // Call the REAL active tick method + previewAbility.onActiveTick(previewNpc, fakeTarget, previewNpc.worldObj, currentTick); - if (currentTick == 1 && !previewAbility.spawnPreviewDuringWindup()) { - spawnPreviewEntity(); - fireEntities(); + // Simulate physics for movement abilities + simulatePhysics(); + + // Check if the ability signaled completion (phase went to IDLE) + if (previewAbility.getPhase() == AbilityPhase.IDLE) { + transitionToExtended(); + return; } - if (currentTick >= activeDuration) { + // Safety timeout + if (currentTick >= maxPreviewDuration) { transitionToExtended(); } } private void tickExtended() { + // Continue ticking entities so they can finish their animations if (currentTick >= EXTENDED_DURATION) { playing = false; } } private void transitionToActive() { - phase = AbilityPhase.ACTIVE; + executorPhase = ExecutorPhase.ACTIVE; currentTick = 0; previewTelegraph = null; - // Notify ability of execution (for movement abilities like Slam/Charge/Dash) - previewAbility.onPreviewExecute(previewNpc); - - fireEntities(); + // Call the REAL onExecute method (fires entities, initiates movement, etc.) + previewAbility.onExecute(previewNpc, fakeTarget, previewNpc.worldObj); + // Start active animation Animation activeAnim = previewAbility.getActiveAnimation(); if (activeAnim != null && previewNpc != null) { AnimationData data = previewNpc.display.animationData; @@ -293,7 +342,7 @@ public class AbilityPreviewExecutor { } private void transitionToExtended() { - phase = AbilityPhase.IDLE; + executorPhase = ExecutorPhase.EXTENDED; currentTick = 0; if (previewNpc != null) { @@ -302,26 +351,40 @@ public class AbilityPreviewExecutor { } } - private void spawnPreviewEntity() { - Entity entity = previewAbility.createPreviewEntity(previewNpc); - if (entity != null) { - previewEntities.add(entity); - if (parentGui != null) { - parentGui.addPreviewEntity(entity); - } - } - } + /** + * Simulate basic physics for movement abilities (Slam, Charge, Dash). + * Applies gravity, drag, and ground clamping to NPC position. + */ + private void simulatePhysics() { + if (!previewAbility.hasAbilityMovement()) return; + if (previewNpc == null) return; - 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(); - } + // Save previous position for interpolation + previewNpc.prevPosX = previewNpc.posX; + previewNpc.prevPosY = previewNpc.posY; + previewNpc.prevPosZ = previewNpc.posZ; + + // Apply velocity + previewNpc.posX += previewNpc.motionX; + previewNpc.posY += previewNpc.motionY; + previewNpc.posZ += previewNpc.motionZ; + + // Apply gravity + previewNpc.motionY -= 0.08; + previewNpc.motionY *= 0.98; + + // Apply horizontal drag + previewNpc.motionX *= 0.91; + previewNpc.motionZ *= 0.91; + + // Ground clamp: if below start position and falling, stop + if (previewNpc.posY < npcStartY && previewNpc.motionY < 0) { + previewNpc.posY = npcStartY; + previewNpc.motionY = 0; + previewNpc.onGround = true; } + + previewNpc.fallDistance = 0; } private void tickEntities() { @@ -339,12 +402,38 @@ public class AbilityPreviewExecutor { } } + // ==================== PreviewEntityHandler ==================== + + @Override + public void onEntitySpawned(Entity entity) { + if (entity == null) return; + previewEntities.add(entity); + if (parentGui != null) { + parentGui.addPreviewEntity(entity); + } + } + + @Override + public void onEntityRemoved(Entity entity) { + if (entity == null) return; + previewEntities.remove(entity); + if (parentGui != null) { + parentGui.removePreviewEntity(entity); + } + } + // ==================== GETTERS ==================== public boolean isPlaying() { return playing; } public boolean isPaused() { return paused; } public boolean isActive() { return playing || paused; } - public AbilityPhase getPhase() { return phase; } + public AbilityPhase getPhase() { + switch (executorPhase) { + case WINDUP: return AbilityPhase.WINDUP; + case ACTIVE: return AbilityPhase.ACTIVE; + default: return AbilityPhase.IDLE; + } + } public int getCurrentTick() { return currentTick; } public TelegraphInstance getTelegraph() { return previewTelegraph; } public List getPreviewEntities() { return previewEntities; } @@ -356,11 +445,11 @@ public class AbilityPreviewExecutor { return "Stopped"; } else if (paused) { return "Paused"; - } else if (phase == AbilityPhase.WINDUP) { + } else if (executorPhase == ExecutorPhase.WINDUP) { return "Windup: " + currentTick + "/" + (previewAbility != null ? previewAbility.getWindUpTicks() : 0); - } else if (phase == AbilityPhase.ACTIVE) { - return "Active: " + currentTick + "/" + activeDuration; - } else if (phase == AbilityPhase.IDLE && playing) { + } else if (executorPhase == ExecutorPhase.ACTIVE) { + return "Active: " + currentTick + "/" + maxPreviewDuration; + } else if (executorPhase == ExecutorPhase.EXTENDED) { return "Extended: " + currentTick + "/" + EXTENDED_DURATION; } return ""; diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java index ea8dcc0b5..3d0573bf2 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiAbilityInterface.java @@ -11,10 +11,7 @@ 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; @@ -50,7 +47,6 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { private GuiNpcButton btnLeft, btnRight; // ==================== NPC STATE ==================== - public ModelData playerdata; public EntityNPCInterface npc; /** NPC starting position (saved when preview starts, used to track movement) */ @@ -74,9 +70,17 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { public int yOffset = 0; public GuiAbilityInterface(EntityNPCInterface npc) { - super(npc); + this(npc, true); + } + + /** + * @param npc The NPC for preview rendering + * @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden. + * Use false when opened from the global menu without a real NPC. + */ + public GuiAbilityInterface(EntityNPCInterface npc, boolean hasMenuNpc) { + super(hasMenuNpc ? npc : null); this.npc = npc; - this.playerdata = ((EntityCustomNpc) npc).modelData; this.drawDefaultBackground = false; CAMERA_ZOOM = 30f; @@ -126,20 +130,17 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { * Draw the 3D preview with NPC and entities. */ protected void drawPreview(int mouseX, int mouseY, float partialTicks) { + if (hasSubGui()) + return; + GL11.glColor4f(1, 1, 1, 1); // Enable scissor to clip rendering to preview area GL11.glEnable(GL11.GL_SCISSOR_TEST); setScissorClip(previewX, previewY, previewWidth, previewHeight); - // 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); + // Always use the standard NPC animation renderer for ability preview + EntityLivingBase renderEntity = this.npc; // Set NPC facing direction (affects anchor points and visual facing) npc.prevRenderYawOffset = npc.renderYawOffset = NPC_FACING_YAW; @@ -195,11 +196,7 @@ public class GuiAbilityInterface extends GuiNPCInterface2 { 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); - } + RenderManager.instance.renderEntityWithPosYaw(renderEntity, npcDeltaX, npcDeltaY, npcDeltaZ, 0.0F, partialTicks); // Render preview entities at their positions relative to NPC start position renderPreviewEntities(partialTicks); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java index 54ca9da5d..cd3e7077c 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiContainerNPCInterface.java @@ -246,7 +246,10 @@ public abstract class GuiContainerNPCInterface extends GuiContainer { } public void closeSubGui(SubGuiInterface gui) { - subgui = null; + // Only null out subgui if it wasn't replaced by a new one during subGuiClosed + if (subgui == gui) { + subgui = null; + } } public boolean hasSubGui() { diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java index 0bf481ffb..f9b3df568 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScroll.java @@ -104,8 +104,10 @@ public class GuiCustomScroll extends GuiScreen { GL11.glTranslatef(guiLeft, guiTop, 0.0F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - if (selectable) + if (selectable && !hasSubGUI) hover = getMouseOver(i, j); + else if (hasSubGUI) + hover = -1; drawItems(); @@ -198,7 +200,8 @@ public class GuiCustomScroll extends GuiScreen { int k = (14 * i + 4) - scrollY; if (k >= 4 && k + 12 < ySize) { int xOffset = scrollHeight < ySize - 8 ? 0 : 10; - String displayString = StatCollector.translateToLocal(list.get(i)); + String rawEntry = list.get(i); + String displayString = StatCollector.translateToLocal(rawEntry); String text = ""; float maxWidth = (xSize + xOffset - 8) * 0.8f; @@ -213,7 +216,13 @@ public class GuiCustomScroll extends GuiScreen { text += "..."; } else text = displayString; - if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { + + // Entries with a custom color are non-interactive (headers/separators) + Integer customColor = colors.get(rawEntry); + if (customColor != null) { + if (!text.isEmpty()) + fontRendererObj.drawString(text, j, k, customColor); + } else if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff); drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff); drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff); @@ -237,13 +246,17 @@ public class GuiCustomScroll extends GuiScreen { private int getMouseOver(int i, int j) { i -= guiLeft; j -= guiTop; - //fontRenderer.drawString(".", i , j, 0xffffff); if (i >= 4 && i < xSize - 4 && j >= 4 && j < ySize) { for (int j1 = 0; j1 < list.size(); j1++) { if (!mouseInOption(i, j, j1)) { continue; } + // Skip non-interactive entries (colored headers/separators) + if (colors.containsKey(list.get(j1))) { + continue; + } + return j1; } @@ -365,6 +378,13 @@ public class GuiCustomScroll extends GuiScreen { return this; } + public void setSelectable(boolean selectable) { + this.selectable = selectable; + if (!selectable) { + hover = -1; + } + } + public boolean isMouseOver(int x, int y) { return x >= this.guiLeft && x <= this.guiLeft + this.xSize && y >= this.guiTop && y <= this.guiTop + this.ySize; } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java index a69d449e7..b147a3af9 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollCloner.java @@ -1,5 +1,6 @@ package noppes.npcs.client.gui.util; +import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.StatCollector; import noppes.npcs.client.gui.GuiNpcMobSpawner; import noppes.npcs.controllers.data.Tag; @@ -7,10 +8,10 @@ import noppes.npcs.controllers.data.Tag; import java.util.UUID; public class GuiCustomScrollCloner extends GuiCustomScroll { - private final GuiNpcMobSpawner parent; + private final IClonerGui parent; - public GuiCustomScrollCloner(GuiNpcMobSpawner parent, int id) { - super(parent, id); + public GuiCustomScrollCloner(IClonerGui parent, int id) { + super((GuiScreen) parent, id); this.parent = parent; } @@ -38,24 +39,25 @@ public class GuiCustomScrollCloner extends GuiCustomScroll { text += "..."; } else text = displayString; - if ((multipleSelection && selectedList.contains(text)) || (!multipleSelection && selected == i)) { + int itemColor = this.colors.getOrDefault(list.get(i), 0xffffff); + if ((multipleSelection && selectedList.contains(list.get(i))) || (!multipleSelection && selected == i)) { drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff); drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff); drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff); drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k + 10, 0xffffffff); - fontRendererObj.drawString(text, j, k, this.colors.getOrDefault(text, 0xffffff)); + fontRendererObj.drawString(text, j, k, itemColor); } else if (i == hover) { fontRendererObj.drawString(text, j, k, 0x00ff00); } else { - fontRendererObj.drawString(text, j, k, this.colors.getOrDefault(text, 0xffffff)); + fontRendererObj.drawString(text, j, k, itemColor); } - if ((this.parent.getShowingClones() == 0 || this.parent.getShowingClones() == 2) && this.parent.tagMap != null) { + if ((parent.getShowingClones() == 0 || parent.getShowingClones() == 2) && parent.getTagMap() != null) { int tagStartX = j + fontRendererObj.getStringWidth(displayString) + 3; if (GuiNpcMobSpawner.displayTags == 0 || GuiNpcMobSpawner.displayTags == 1) { - if (this.parent.tagMap.hasClone(list.get(i))) { - for (UUID tagUUID : this.parent.tagMap.getUUIDsList(list.get(i))) { - Tag tag = this.parent.tags.get(tagUUID); + if (parent.getTagMap().hasClone(list.get(i))) { + for (UUID tagUUID : parent.getTagMap().getUUIDsList(list.get(i))) { + Tag tag = parent.getTags().get(tagUUID); if (tag != null) { if (GuiNpcMobSpawner.displayTags == 1 || !tag.getIsHidden()) { fontRendererObj.drawString("[" + tag.name + "]", tagStartX, k, tag.color); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollIcons.java b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollIcons.java new file mode 100644 index 000000000..78686dac0 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiCustomScrollIcons.java @@ -0,0 +1,108 @@ +package noppes.npcs.client.gui.util; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import org.lwjgl.opengl.GL11; + +import java.util.ArrayList; +import java.util.List; + +public class GuiCustomScrollIcons extends GuiCustomScroll { + public static final int ICON_NONE = 0; + public static final int ICON_TAB = 1; + public static final int ICON_FOLDER = 2; + + private static final ResourceLocation TAB_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/cloner/tab.png"); + private static final ResourceLocation FOLDER_TEXTURE = new ResourceLocation("customnpcs", "textures/gui/cloner/folder.png"); + + private static final int ICON_RENDER_SIZE = 10; + private static final int ICON_PADDING = 14; + + private List iconTypes = new ArrayList<>(); + + public GuiCustomScrollIcons(GuiScreen parent, int id) { + super(parent, id); + } + + public void setListWithIcons(List names, List icons) { + this.setUnsortedList(names); + this.iconTypes = new ArrayList<>(icons); + } + + @Override + protected void drawItems() { + Minecraft mc = Minecraft.getMinecraft(); + for (int i = 0; i < list.size(); i++) { + int j = 4; + int k = (14 * i + 4) - scrollY; + if (k >= 4 && k + 12 < ySize) { + int xOffset = scrollHeight < ySize - 8 ? 0 : 10; + + int iconType = (i < iconTypes.size()) ? iconTypes.get(i) : ICON_NONE; + int textX = j; + if (iconType != ICON_NONE) { + textX = j + ICON_PADDING; + } + + // Draw icon texture + if (iconType == ICON_FOLDER || iconType == ICON_TAB) { + ResourceLocation tex = (iconType == ICON_FOLDER) ? FOLDER_TEXTURE : TAB_TEXTURE; + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mc.getTextureManager().bindTexture(tex); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + drawFullTexture(j, k - 1, ICON_RENDER_SIZE, ICON_RENDER_SIZE); + GL11.glDisable(GL11.GL_BLEND); + } + + // Draw text + String displayString = StatCollector.translateToLocal(list.get(i)); + String text = ""; + float maxWidth = (xSize + xOffset - 8 - (iconType != ICON_NONE ? ICON_PADDING : 0)) * 0.8f; + if (fontRendererObj.getStringWidth(displayString) > maxWidth) { + for (int h = 0; h < displayString.length(); h++) { + char c = displayString.charAt(h); + text += c; + if (fontRendererObj.getStringWidth(text) > maxWidth) + break; + } + if (displayString.length() > text.length()) + text += "..."; + } else { + text = displayString; + } + + int itemColor = this.colors.getOrDefault(list.get(i), 0xffffff); + + if ((multipleSelection && selectedList.contains(list.get(i))) || (!multipleSelection && selected == i)) { + drawVerticalLine(j - 2, k - 4, k + 10, 0xffffffff); + drawVerticalLine(j + xSize - 18 + xOffset, k - 4, k + 10, 0xffffffff); + drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k - 3, 0xffffffff); + drawHorizontalLine(j - 2, j + xSize - 18 + xOffset, k + 10, 0xffffffff); + fontRendererObj.drawString(text, textX, k, itemColor); + } else if (i == hover) { + fontRendererObj.drawString(text, textX, k, 0x00ff00); + } else { + fontRendererObj.drawString(text, textX, k, itemColor); + } + } + } + } + + /** + * Draw a full texture (UV 0,0 to 1,1) scaled to the given width/height. + * Works with any texture size (not just 256x256). + */ + private void drawFullTexture(int x, int y, int w, int h) { + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(x, y + h, 0, 0, 1); + tessellator.addVertexWithUV(x + w, y + h, 0, 1, 1); + tessellator.addVertexWithUV(x + w, y, 0, 1, 0); + tessellator.addVertexWithUV(x, y, 0, 0, 0); + tessellator.draw(); + } +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java b/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java new file mode 100644 index 000000000..750c60668 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/GuiDirectory.java @@ -0,0 +1,206 @@ +package noppes.npcs.client.gui.util; + +/** + * Abstract base class for fullscreen directory-browsing GUIs. + * Provides a configurable three-panel layout (left nav, center content, right actions) + * with percentage-based sizing, panel backgrounds/borders, and an optional resizable divider. + * + * Subclasses override abstract hooks to populate each panel region. + * Designed for reuse across Cloner, Quest Manager, Dialog Manager, etc. + */ +public abstract class GuiDirectory extends GuiNPCInterface implements ICustomScrollListener, ISubGuiListener { + + // ===== LAYOUT CONFIG (subclasses may override in constructor) ===== + protected float leftPanelPercent = 0.20f; + protected float rightPanelPercent = 0.10f; + protected int minLeftPanelW = 80; + protected int minRightPanelW = 40; + protected int minCenterW = 100; + + // ===== LAYOUT CONSTANTS ===== + protected int pad = 10; + protected int topBarH = 24; + protected int gap = 4; + protected int btnH = 20; + + // ===== PANEL COLORS ===== + protected int panelBg = 0xC0101010; + protected int panelBorder = 0xFF333333; + protected int topBarBg = 0xC0181818; + + // ===== COMPUTED LAYOUT (populated by computeLayout) ===== + protected int originX, originY, usableW, usableH; + protected int leftPanelW, rightPanelW; + protected int contentX, contentY, contentW, contentH; + protected int rightX; + + // ===== OPTIONAL RESIZABLE DIVIDER (between left and center) ===== + protected boolean enableDivider = false; + protected int dividerWidth = 5; + protected int dividerLineHeight = 20; + protected int minDividerPanelW = 50; + private int dividerOffset; + private boolean isDragging = false; + private int dragStartX; + + // ===== CONSTRUCTOR ===== + public GuiDirectory() { + super(); + closeOnEsc = true; + drawDefaultBackground = true; + } + + // ===== LAYOUT COMPUTATION ===== + protected void computeLayout() { + originX = pad; + originY = pad; + usableW = width - 2 * pad; + usableH = height - 2 * pad; + + leftPanelW = Math.max(minLeftPanelW, (int)(usableW * leftPanelPercent)); + rightPanelW = Math.max(minRightPanelW, (int)(usableW * rightPanelPercent)); + + if (rightPanelPercent <= 0) { + rightPanelW = 0; + } + + int gapCount = rightPanelW > 0 ? 3 : 2; + contentW = usableW - leftPanelW - rightPanelW - gapCount * gap; + if (contentW < minCenterW) { + contentW = minCenterW; + } + + contentX = originX + leftPanelW + gap; + contentY = originY + topBarH + gap; + contentH = usableH - topBarH - gap; + rightX = contentX + contentW + gap; + + if (enableDivider && dividerOffset == 0) { + dividerOffset = leftPanelW; + } + } + + // ===== INIT GUI ===== + @Override + public void initGui() { + super.initGui(); + computeLayout(); + initTopBar(originY + 2); + initLeftPanel(); + initCenterPanel(); + if (rightPanelW > 0) { + initRightPanel(contentY + 4); + } + } + + // ===== DRAWING ===== + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawTopBar(); + drawPanels(); + if (enableDivider) { + drawDivider(mouseX, mouseY); + } + super.drawScreen(mouseX, mouseY, partialTicks); + drawOverlay(mouseX, mouseY, partialTicks); + } + + protected void drawTopBar() { + GuiUtil.drawRectD(originX, originY, originX + usableW, originY + topBarH, topBarBg); + } + + protected void drawPanels() { + // Left nav panel border + GuiUtil.drawRectD(originX - 1, contentY - 1, originX + leftPanelW + 1, originY + usableH + 1, panelBorder); + + // Right action panel border (if present) + if (rightPanelW > 0) { + GuiUtil.drawRectD(rightX - 1, contentY - 1, rightX + rightPanelW + 1, originY + usableH + 1, panelBorder); + } + } + + protected void drawDivider(int mouseX, int mouseY) { + if (!enableDivider) return; + int divX = originX + dividerOffset; + int regionTop = contentY; + int regionHeight = contentH; + int handleTop = regionTop + (regionHeight - dividerLineHeight) / 2; + drawRect(divX + 1, handleTop, divX + dividerWidth - 1, handleTop + dividerLineHeight, 0xFF707070); + } + + /** Override for extra drawing after super.drawScreen (e.g. status text) */ + protected void drawOverlay(int mouseX, int mouseY, float partialTicks) { + } + + // ===== DIVIDER MOUSE HANDLING ===== + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + if (enableDivider && !hasSubGui()) { + int divX = originX + dividerOffset; + int regionTop = contentY; + int handleTop = regionTop + (contentH - dividerLineHeight) / 2; + int handleBottom = handleTop + dividerLineHeight; + if (mouseX >= divX && mouseX <= divX + dividerWidth && + mouseY >= handleTop && mouseY <= handleBottom) { + isDragging = true; + resizingActive = true; + dragStartX = mouseX; + return; + } + } + super.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + public void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { + if (isDragging) { + int dx = mouseX - dragStartX; + dragStartX = mouseX; + dividerOffset += dx; + + int maxOffset = (usableW - (rightPanelW > 0 ? rightPanelW + gap : 0)) - dividerWidth - minDividerPanelW; + dividerOffset = Math.max(minDividerPanelW, Math.min(dividerOffset, maxOffset)); + + onDividerMoved(dividerOffset); + return; + } + super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); + } + + @Override + protected void mouseMovedOrUp(int mouseX, int mouseY, int state) { + if (isDragging) { + isDragging = false; + resizingActive = false; + return; + } + super.mouseMovedOrUp(mouseX, mouseY, state); + } + + /** Called when divider is dragged. Override to update scroll sizes. */ + protected void onDividerMoved(int newOffset) { + } + + // Accessors for divider offset + protected int getDividerOffset() { + return dividerOffset; + } + + protected void setDividerOffset(int offset) { + this.dividerOffset = offset; + } + + // ===== ABSTRACT HOOKS (subclass must implement) ===== + + /** Populate top bar buttons. topBtnY is the y-coordinate for the button row. */ + protected abstract void initTopBar(int topBtnY); + + /** Populate the left navigation panel (scrolls, search fields, buttons). */ + protected abstract void initLeftPanel(); + + /** Populate the center content panel (main scroll list). */ + protected abstract void initCenterPanel(); + + /** Populate the right action panel. startY is the first button y-coordinate. */ + protected abstract void initRightPanel(int startY); +} diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiMenuSideButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiMenuSideButton.java index 0aa6c7d3d..94398bb60 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiMenuSideButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiMenuSideButton.java @@ -15,6 +15,7 @@ public class GuiMenuSideButton extends GuiNpcButton { public boolean active; public boolean rightSided; + public int textColor = -1; public ItemStack renderStack; public ResourceLocation renderResource; public int renderIconPosX = 0; @@ -96,13 +97,15 @@ public class GuiMenuSideButton extends GuiNpcButton { text += "..."; } else text = displayString; - if (active) { - drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffffa0); - } else if (field_146123_n) { - drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xffffa0); + int color; + if (textColor != -1) { + color = textColor; + } else if (active || field_146123_n) { + color = 0xffffa0; } else { - drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, 0xe0e0e0); + color = 0xe0e0e0; } + drawCenteredString(fontrenderer, text, xPosition + width / 2, yPosition + (height - 8) / 2, color); } @Override diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java b/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java index cef818647..5ca2edfb0 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiModelInterface2.java @@ -30,10 +30,18 @@ public class GuiModelInterface2 extends GuiNPCInterface2 { public EntityNPCInterface npc; public GuiModelInterface2(EntityNPCInterface npc) { - super(npc); + this(npc, true); + } + + /** + * @param npc The NPC for preview rendering + * @param hasMenuNpc If false, the top menu tabs (Display, Stats, etc.) are hidden. + * Use false when opened from the global menu without a real NPC. + */ + public GuiModelInterface2(EntityNPCInterface npc, boolean hasMenuNpc) { + super(hasMenuNpc ? npc : null); this.npc = npc; playerdata = ((EntityCustomNpc) npc).modelData; - //xSize = 380; drawDefaultBackground = false; } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java index 4ddd820c0..cf9143c66 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java @@ -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.Consumer; import java.util.function.Supplier; public abstract class GuiNPCInterface extends GuiScreen { @@ -52,6 +53,7 @@ public abstract class GuiNPCInterface extends GuiScreen { public Supplier closeOnEscSupplier = null; public int guiLeft, guiTop, xSize, ySize; private SubGuiInterface subgui; + private Consumer pendingSubGuiResult; public int mouseX, mouseY, mouseScroll; public float bgScale = 1; public float bgScaleX = 1; @@ -519,8 +521,25 @@ public abstract class GuiNPCInterface extends GuiScreen { initGui(); } + /** + * Open a sub-gui with a result handler that will be called when the sub-gui closes. + * The handler survives initGui() rebuilds since it lives on the parent, not the builder. + */ + public void setSubGuiWithResult(SubGuiInterface gui, Consumer resultHandler) { + this.pendingSubGuiResult = resultHandler; + setSubGui(gui); + } + public void closeSubGui(SubGuiInterface gui) { - subgui = null; + if (pendingSubGuiResult != null) { + Consumer handler = pendingSubGuiResult; + pendingSubGuiResult = null; + handler.accept(gui); + } + // Only null out subgui if it wasn't replaced by a new one during subGuiClosed + if (subgui == gui) { + subgui = null; + } initGui(); } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java b/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java index d09bddecf..4ebafd54f 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcButton.java @@ -2,6 +2,7 @@ package noppes.npcs.client.gui.util; import kamkeel.npcs.util.TextSplitter; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderHelper; @@ -151,8 +152,23 @@ public class GuiNpcButton extends GuiButton { public void drawButton(Minecraft mc, int mouseX, int mouseY) { if (!this.visible) return; + // Auto-truncate display text if wider than button + String original = this.displayString; + FontRenderer fr = mc.fontRenderer; + if (fr != null) { + int maxTextWidth = this.width - 6; + if (fr.getStringWidth(original) > maxTextWidth) { + String ellipsis = "..."; + int targetWidth = maxTextWidth - fr.getStringWidth(ellipsis); + if (targetWidth > 0) { + this.displayString = fr.trimStringToWidth(original, targetWidth) + ellipsis; + } + } + } // First, draw the button normally using the superclass method. super.drawButton(mc, mouseX, mouseY); + // Restore original display string + this.displayString = original; // Then, if an icon texture is set, draw it. if (iconTexture != null) { mc.getTextureManager().bindTexture(iconTexture); diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java b/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java index f620e1e63..60b4afdb6 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNpcLabel.java @@ -1,18 +1,32 @@ package noppes.npcs.client.gui.util; +import kamkeel.npcs.util.TextSplitter; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.ScaledResolution; +import net.minecraft.client.renderer.RenderHelper; import net.minecraft.util.StatCollector; import noppes.npcs.client.CustomNpcResourceListener; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; -public class GuiNpcLabel { +import java.util.Iterator; +import java.util.List; + +public class GuiNpcLabel extends Gui { public String label; public int x, y, color; public boolean enabled = true; public int id; public boolean drawShadow = false; + // Hover text support + public String hoverableText = ""; + private boolean wasHovered = false; + private int hoverCount = 0; + public GuiNpcLabel(int id, Object label, int x, int y, int color) { this.id = id; this.label = StatCollector.translateToLocal(label.toString()); @@ -25,6 +39,10 @@ public class GuiNpcLabel { this(id, label, x, y, CustomNpcResourceListener.DefaultTextColor); } + public void setHoverText(String text) { + this.hoverableText = text; + } + public void drawLabel(GuiScreen gui, FontRenderer fontRenderer) { if (enabled) fontRenderer.drawString(label, x, y, color, drawShadow); @@ -34,4 +52,119 @@ public class GuiNpcLabel { int size = Minecraft.getMinecraft().fontRenderer.getStringWidth(label); x += (width - size) / 2; } + + public boolean isMouseOver(int mouseX, int mouseY, FontRenderer fr) { + int width = fr.getStringWidth(label); + return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + 10; + } + + /** + * Draws hover tooltip if the mouse is over this label. + * @param localMouseX Mouse X in scroll-local coordinates (for hit testing) + * @param localMouseY Mouse Y in scroll-local coordinates (for hit testing) + * @param screenMouseX Mouse X in screen coordinates (for tooltip positioning) + * @param screenMouseY Mouse Y in screen coordinates (for tooltip positioning) + * @param hasSubGui Whether a sub-gui is open + * @param fr FontRenderer for measuring label width + */ + public void drawHover(int localMouseX, int localMouseY, int screenMouseX, int screenMouseY, boolean hasSubGui, FontRenderer fr) { + if (hasSubGui || hoverableText.isEmpty()) return; + + boolean hovered = isMouseOver(localMouseX, localMouseY, fr); + if (!hovered) { + wasHovered = false; + hoverCount = 0; + return; + } + if (!wasHovered) { + wasHovered = true; + hoverCount = 0; + } + if (hoverCount < 65) hoverCount++; + + if (hoverCount > 60) { + GL11.glPushMatrix(); + Minecraft mc = Minecraft.getMinecraft(); + String displayString = StatCollector.translateToLocal(hoverableText); + GL11.glColor4f(1, 1, 1, 1); + List lines = TextSplitter.splitText(displayString, 30); + drawHoveringText(lines, screenMouseX, screenMouseY, mc); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glPopMatrix(); + } + } + + @SuppressWarnings("rawtypes") + protected void drawHoveringText(List textLines, int x, int y, Minecraft mc) { + if (mc.fontRenderer == null || textLines.isEmpty()) + return; + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + + int maxWidth = 0; + Iterator iterator = textLines.iterator(); + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int lineWidth = mc.fontRenderer.getStringWidth(s); + if (lineWidth > maxWidth) { + maxWidth = lineWidth; + } + } + + int j2 = x + 12; + int k2 = y - 12; + int maxHeight = 8; + + if (textLines.size() > 1) { + maxHeight += 2 + (textLines.size() - 1) * 10; + } + + ScaledResolution scaledRes = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + int screenWidth = scaledRes.getScaledWidth(); + int screenHeight = scaledRes.getScaledHeight(); + + if (j2 + maxWidth + 6 > screenWidth) { + j2 = x - maxWidth - 16; + } + if (j2 < 4) { + j2 = 4; + } + if (k2 + maxHeight + 6 > screenHeight) { + k2 = screenHeight - maxHeight - 6; + } + if (k2 < 4) { + k2 = 4; + } + + this.zLevel = 300.0F; + int j1 = -267386864; + this.drawGradientRect(j2 - 3, k2 - 4, j2 + maxWidth + 3, k2 - 3, j1, j1); + this.drawGradientRect(j2 - 3, k2 + maxHeight + 3, j2 + maxWidth + 3, k2 + maxHeight + 4, j1, j1); + this.drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 + maxHeight + 3, j1, j1); + this.drawGradientRect(j2 - 4, k2 - 3, j2 - 3, k2 + maxHeight + 3, j1, j1); + this.drawGradientRect(j2 + maxWidth + 3, k2 - 3, j2 + maxWidth + 4, k2 + maxHeight + 3, j1, j1); + int k1 = 1347420415; + int l1 = (k1 & 16711422) >> 1 | k1 & -16777216; + this.drawGradientRect(j2 - 3, k2 - 3 + 1, j2 - 3 + 1, k2 + maxHeight + 3 - 1, k1, l1); + this.drawGradientRect(j2 + maxWidth + 2, k2 - 3 + 1, j2 + maxWidth + 3, k2 + maxHeight + 3 - 1, k1, l1); + this.drawGradientRect(j2 - 3, k2 - 3, j2 + maxWidth + 3, k2 - 3 + 1, k1, k1); + this.drawGradientRect(j2 - 3, k2 + maxHeight + 2, j2 + maxWidth + 3, k2 + maxHeight + 3, l1, l1); + + for (int i2 = 0; i2 < textLines.size(); ++i2) { + String s1 = (String) textLines.get(i2); + mc.fontRenderer.drawStringWithShadow(s1, j2, k2, -1); + if (i2 == 0) { + k2 += 2; + } + k2 += 10; + } + + this.zLevel = 0.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } } diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java b/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java index 3273f1f6c..ab6e612d4 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScrollWindow.java @@ -97,6 +97,11 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC } public void mouseClicked(int i, int j, int k) { + // Ignore clicks outside the visible scroll window area + if (i < xPos || i > xPos + clipWidth || j < yPos || j > yPos + clipHeight) { + return; + } + i = i - xPos; j = (int) (j - yPos + scrollY); @@ -246,6 +251,12 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC } GL11.glPopMatrix(); + + // Draw hover texts in screen space (after scissor/translation are undone) + // so tooltips are not clipped and are positioned correctly + if (isMouseOver(mouseX, mouseY)) { + drawHoverTexts(mouseX, mouseY); + } } public void drawScreen(int mouseX, int mouseY, float partialTicks, int mouseScroll) { @@ -275,8 +286,26 @@ public class GuiScrollWindow extends GuiScreen implements ITextfieldListener, IC } for (GuiNpcButton button : buttons.values()) { button.updateSubGUI(subGui); + } + } + + /** + * Draws hover texts for buttons in screen space (called after GL scissor/translate are undone). + * Hover state was already computed during drawComponents with scroll-local coords. + */ + private void drawHoverTexts(int mouseX, int mouseY) { + boolean subGui = parent.hasSubGui(); + for (GuiNpcButton button : buttons.values()) { if (!button.hoverableText.isEmpty()) { - button.drawHover(i, j, subGui); + button.drawHover(mouseX, mouseY, subGui); + } + } + // Label hover: convert screen mouse to scroll-local coords for hit testing + int localMouseX = mouseX - xPos; + int localMouseY = (int) (mouseY - yPos + scrollY); + for (GuiNpcLabel label : labels.values()) { + if (!label.hoverableText.isEmpty()) { + label.drawHover(localMouseX, localMouseY, mouseX, mouseY, subGui, fontRendererObj); } } } diff --git a/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java b/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java new file mode 100644 index 000000000..db4989b56 --- /dev/null +++ b/src/main/java/noppes/npcs/client/gui/util/IClonerGui.java @@ -0,0 +1,13 @@ +package noppes.npcs.client.gui.util; + +import noppes.npcs.controllers.data.Tag; +import noppes.npcs.controllers.data.TagMap; + +import java.util.HashMap; +import java.util.UUID; + +public interface IClonerGui { + int getShowingClones(); + HashMap getTags(); + TagMap getTagMap(); +} diff --git a/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java b/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java index 64b37340f..7f9fdd19b 100644 --- a/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java +++ b/src/main/java/noppes/npcs/client/renderer/blocks/BlockBeamRenderer.java @@ -26,8 +26,8 @@ public class BlockBeamRenderer extends BlockRendererInterface { public void renderTileEntityAt(TileEntity var1, double var2, double var4, double var6, float var8) { TileVariant tile = (TileVariant) var1; - GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPushMatrix(); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glTranslatef((float) var2 + 0.5f, (float) var4 + 1.5f, (float) var6 + 0.5f); //GL11.glScalef(1.2f, 1.1f, 1.2f); GL11.glRotatef(180, 0, 0, 1); diff --git a/src/main/java/noppes/npcs/config/ConfigClient.java b/src/main/java/noppes/npcs/config/ConfigClient.java index c24a2e301..d8c093382 100644 --- a/src/main/java/noppes/npcs/config/ConfigClient.java +++ b/src/main/java/noppes/npcs/config/ConfigClient.java @@ -22,6 +22,9 @@ public class ConfigClient { /** * General Properties **/ + public static Property AllowClientScriptsProperty; + public static boolean AllowClientScripts = true; + public static Property CacheLifeProperty; public static int CacheLife = 10; @@ -185,6 +188,9 @@ public class ConfigClient { // General + AllowClientScriptsProperty = config.get(GENERAL, "Allow Client Scripts", true, "Allow the server to run scripts on the client. If disabled, no server scripts will execute client-side."); + AllowClientScripts = AllowClientScriptsProperty.getBoolean(true); + CacheLifeProperty = config.get(GENERAL, "Cache Life", 10, "How long should downloaded imagery data be saved client side? (In minutes)"); CacheLife = CacheLifeProperty.getInt(10); diff --git a/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java b/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java index 807190816..03a690bcd 100644 --- a/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java +++ b/src/main/java/noppes/npcs/containers/ContainerNPCTrader.java @@ -127,15 +127,11 @@ public class ContainerNPCTrader extends ContainerNpcInterface { givePlayer(soldItem, entityplayer); role.addPurchase(i, entityplayer.getDisplayName()); - // Sync updated data after purchase - // For per-player stocks: sync only to the purchasing player - // For shared stocks: consumeStock() handles sync (market-wide or local) + // Always sync the purchasing player's data (balance + stock) after trade. + // For shared stocks, consumeStock() syncs stock to other viewers, + // but the purchasing player's balance still needs an explicit sync. if (entityplayer instanceof EntityPlayerMP) { - if (role.stock.perPlayer) { - // Per-player: only sync to purchasing player (their own stock/balance) - role.syncToPlayer((EntityPlayerMP) entityplayer); - } - // Shared stock sync is already handled in consumeStock() + role.syncToPlayer((EntityPlayerMP) entityplayer); } return soldItem; diff --git a/src/main/java/noppes/npcs/controllers/AnimationController.java b/src/main/java/noppes/npcs/controllers/AnimationController.java index c6837b6c7..b4203b452 100644 --- a/src/main/java/noppes/npcs/controllers/AnimationController.java +++ b/src/main/java/noppes/npcs/controllers/AnimationController.java @@ -120,12 +120,9 @@ public class AnimationController implements IAnimationHandler { } } - /** - * Load a single built-in animation by name from assets folder. - */ - private void loadBuiltInAnimation(String animName) throws Exception { - String resourcePath = BUILTIN_ANIMATIONS_PATH + "/" + animName + ".json"; - try (InputStream stream = CustomNpcs.class.getResourceAsStream(resourcePath)) { + public void loadBuiltInAnimation(Class modClass, String path, String animName) throws Exception { + String resourcePath = path + "/" + animName + ".json"; + try (InputStream stream = modClass.getResourceAsStream(resourcePath)) { if (stream == null) { return; } @@ -150,6 +147,13 @@ public class AnimationController implements IAnimationHandler { } } + /** + * Load a single built-in animation by name from assets folder. + */ + private void loadBuiltInAnimation(String animName) throws Exception { + loadBuiltInAnimation(CustomNpcs.class, BUILTIN_ANIMATIONS_PATH, animName); + } + private void loadAnimations() { animations.clear(); @@ -314,6 +318,10 @@ public class AnimationController implements IAnimationHandler { } public IAnimation get(String name) { + return get(name, false); + } + + public IAnimation get(String name, boolean builtIn) { // Check user/custom animations first (allows overriding built-in) for (Map.Entry entry : animations.entrySet()) { if (entry.getValue().name.equalsIgnoreCase(name)) { @@ -321,10 +329,13 @@ public class AnimationController implements IAnimationHandler { } } // Then check built-in animations - BuiltInAnimation builtIn = builtInAnimations.get(name.toLowerCase()); - if (builtIn != null) { - return builtIn; + if (builtIn) { + BuiltInAnimation builtInAnim = builtInAnimations.get(name.toLowerCase()); + if (builtInAnim != null) { + return builtInAnim; + } } + return null; } diff --git a/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java b/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java new file mode 100644 index 000000000..5a9d32ed3 --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/ScriptConfigSync.java @@ -0,0 +1,25 @@ +package noppes.npcs.controllers; + +import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.config.ConfigScript; + +/** + * Server-side utility for syncing script configuration to clients. + * + * This class is SERVER-SIDE ONLY. Client reads via ScriptClientConfig. + */ +public class ScriptConfigSync { + + /** + * Write script config to NBT for sending to client. + * Called on server side when building login packet. + */ + public static NBTTagCompound writeToNBT(NBTTagCompound compound) { + compound.setBoolean("ScriptingEnabled", ConfigScript.ScriptingEnabled); + compound.setBoolean("RunLoadedScriptsFirst", ConfigScript.RunLoadedScriptsFirst); + compound.setBoolean("GlobalPlayerScripts", ConfigScript.GlobalPlayerScripts); + compound.setBoolean("GlobalForgeScripts", ConfigScript.GlobalForgeScripts); + compound.setBoolean("GlobalNPCScripts", ConfigScript.GlobalNPCScripts); + return compound; + } +} diff --git a/src/main/java/noppes/npcs/controllers/ScriptContainer.java b/src/main/java/noppes/npcs/controllers/ScriptContainer.java index 1b13b20c0..9674c8b04 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptContainer.java +++ b/src/main/java/noppes/npcs/controllers/ScriptContainer.java @@ -3,6 +3,7 @@ package noppes.npcs.controllers; import cpw.mods.fml.common.eventhandler.Event; import jdk.nashorn.api.scripting.ScriptObjectMirror; import net.minecraft.nbt.NBTTagCompound; +import noppes.npcs.CustomNpcs; import noppes.npcs.NBTTags; import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumScriptType; @@ -104,7 +105,7 @@ public class ScriptContainer implements IScriptUnit { if (!this.evaluated) { // build includes first depending on config setting StringBuilder sb = new StringBuilder(); - if (ConfigScript.RunLoadedScriptsFirst) { + if (CustomNpcs.proxy.isRunLoadedScriptsFirst()) { this.appendExternalScripts(sb); } @@ -114,7 +115,7 @@ public class ScriptContainer implements IScriptUnit { } // build includes last if not built first - if (!ConfigScript.RunLoadedScriptsFirst) { + if (!CustomNpcs.proxy.isRunLoadedScriptsFirst()) { this.appendExternalScripts(sb); } this.fullscript = sb.toString(); @@ -158,14 +159,14 @@ public class ScriptContainer implements IScriptUnit { } public void run(EnumScriptType type, Event event) { - if (!ConfigScript.ScriptingEnabled) + if (!CustomNpcs.proxy.isScriptingEnabled()) return; this.run((String) type.function, (Object) event); } public void run(String type, Object event) { - if (!ConfigScript.ScriptingEnabled || errored || !hasCode() || unknownFunctions.contains(type)) + if (!CustomNpcs.proxy.isScriptingEnabled() || errored || !hasCode() || unknownFunctions.contains(type)) return; this.setEngine(handler.getLanguage()); @@ -342,5 +343,10 @@ public class ScriptContainer implements IScriptUnit { public void setErrored(boolean errored) { this.errored = errored; } + + @Override + public boolean isJanino() { + return false; + } } diff --git a/src/main/java/noppes/npcs/controllers/ScriptController.java b/src/main/java/noppes/npcs/controllers/ScriptController.java index af2153cff..546b3680d 100644 --- a/src/main/java/noppes/npcs/controllers/ScriptController.java +++ b/src/main/java/noppes/npcs/controllers/ScriptController.java @@ -73,7 +73,7 @@ public class ScriptController { public ScriptController() { Instance = this; manager = new ScriptEngineManager(); - if (!ConfigScript.ScriptingEnabled) + if (!CustomNpcs.proxy.isScriptingEnabled()) return; LogWriter.info("Script Engines Available:"); diff --git a/src/main/java/noppes/npcs/controllers/ServerCloneController.java b/src/main/java/noppes/npcs/controllers/ServerCloneController.java index ea61a0112..32bd0e15c 100644 --- a/src/main/java/noppes/npcs/controllers/ServerCloneController.java +++ b/src/main/java/noppes/npcs/controllers/ServerCloneController.java @@ -15,6 +15,7 @@ import noppes.npcs.api.IPos; import noppes.npcs.api.IWorld; import noppes.npcs.api.entity.IEntity; import noppes.npcs.api.handler.ICloneHandler; +import noppes.npcs.controllers.data.CloneFolder; import noppes.npcs.controllers.data.TagMap; import noppes.npcs.scripted.CustomNPCsException; import noppes.npcs.scripted.NpcAPI; @@ -27,6 +28,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -34,8 +36,11 @@ import java.util.UUID; public class ServerCloneController implements ICloneHandler { public static ServerCloneController Instance; + protected Map folders = new LinkedHashMap<>(); + public ServerCloneController() { loadClones(); + loadFolders(); } private void loadClones() { @@ -103,6 +108,8 @@ public class ServerCloneController implements ICloneHandler { return clones; } + // ==================== Tab-Based Clone Operations ==================== + public NBTTagCompound getCloneData(ICommandSender player, String name, int tab) { File file = new File(new File(getDir(), tab + ""), name + ".json"); if (!file.exists()) { @@ -194,6 +201,250 @@ public class ServerCloneController implements ICloneHandler { return name; } + // ==================== Folder Registry ==================== + + public void loadFolders() { + folders.clear(); + File dir = getDir(); + File[] files = dir.listFiles(); + if (files != null) { + List folderDirs = new ArrayList<>(); + for (File f : files) { + if (!f.isDirectory()) continue; + String name = f.getName(); + if (name.startsWith("___")) continue; + try { + Integer.parseInt(name); + continue; + } catch (NumberFormatException ignored) { + } + folderDirs.add(f); + } + folderDirs.sort(Comparator.comparing(File::getName)); + for (File f : folderDirs) { + CloneFolder folder = new CloneFolder(f.getName()); + folder.createdDate = f.lastModified(); + folders.put(f.getName(), folder); + } + } + } + + public List getFolderList() { + return new ArrayList<>(folders.values()); + } + + public List getFolderNames() { + return new ArrayList<>(folders.keySet()); + } + + public boolean hasFolder(String name) { + return folders.containsKey(name); + } + + // ==================== Folder CRUD ==================== + + public CloneFolder createFolder(String name) { + if (!CloneFolder.isValidName(name) || folders.containsKey(name)) { + return null; + } + CloneFolder folder = new CloneFolder(name); + File dir = getFolderDir(name); + if (!dir.exists()) { + dir.mkdir(); + } + folders.put(name, folder); + return folder; + } + + public boolean renameFolder(String oldName, String newName) { + if (!folders.containsKey(oldName) || !CloneFolder.isValidName(newName) || folders.containsKey(newName)) { + return false; + } + CloneFolder folder = folders.get(oldName); + File oldDir = getFolderDir(oldName); + File newDir = new File(getDir(), newName); + if (!oldDir.renameTo(newDir)) { + return false; + } + folders.remove(oldName); + folder.name = newName; + folders.put(newName, folder); + return true; + } + + public boolean deleteFolder(String name) { + if (!folders.containsKey(name)) { + return false; + } + List clones = getClones(name); + if (!clones.isEmpty()) { + return false; + } + File dir = getFolderDir(name); + if (dir.exists()) { + File tagMapFile = new File(dir, "___tagmap.dat"); + if (tagMapFile.exists()) tagMapFile.delete(); + File tagMapOld = new File(dir, "___tagmap.dat_old"); + if (tagMapOld.exists()) tagMapOld.delete(); + File tagMapNew = new File(dir, "___tagmap.dat_new"); + if (tagMapNew.exists()) tagMapNew.delete(); + dir.delete(); + } + folders.remove(name); + return true; + } + + // ==================== Folder-Based Clone Operations ==================== + + public File getFolderDir(String folderName) { + return new File(getDir(), folderName); + } + + public List getClones(String folderName) { + List list = new ArrayList<>(); + File dir = getFolderDir(folderName); + if (!dir.exists() || !dir.isDirectory()) + return list; + for (String file : dir.list()) { + if (file.endsWith(".json")) + list.add(file.substring(0, file.length() - 5)); + } + return list; + } + + public List getClonesDate(String folderName) { + List list = new ArrayList<>(); + File dir = getFolderDir(folderName); + if (!dir.exists() || !dir.isDirectory()) + return list; + File[] files = dir.listFiles(); + if (files == null) return list; + Arrays.sort(files, new Comparator() { + public int compare(File f1, File f2) { + return Long.compare(f1.lastModified(), f2.lastModified()); + } + }); + for (File file : files) { + String fileName = file.getName(); + if (fileName.endsWith(".json")) + list.add(fileName.substring(0, fileName.length() - 5)); + } + return list; + } + + public NBTTagCompound getCloneData(ICommandSender player, String name, String folderName) { + File file = new File(getFolderDir(folderName), name + ".json"); + if (!file.exists()) { + if (player != null) + player.addChatMessage(new ChatComponentText("Could not find clone file")); + return null; + } + try { + return NBTJsonUtil.LoadFile(file); + } catch (Exception e) { + LogWriter.error("Error loading: " + file.getAbsolutePath(), e); + if (player != null) + player.addChatMessage(new ChatComponentText(e.getMessage())); + } + return null; + } + + public void saveClone(String folderName, String name, NBTTagCompound compound) { + try { + File dir = getFolderDir(folderName); + if (!dir.exists()) dir.mkdir(); + String filename = name + ".json"; + File file = new File(dir, filename + "_new"); + File file2 = new File(dir, filename); + NBTJsonUtil.SaveFile(file, compound); + addToTagMap(compound, name, folderName); + if (file2.exists()) { + file2.delete(); + } + file.renameTo(file2); + } catch (Exception e) { + LogWriter.except(e); + } + } + + public boolean removeClone(String name, String folderName) { + File file = new File(getFolderDir(folderName), name + ".json"); + if (!file.exists()) + return false; + file.delete(); + removeFromTagMap(name, folderName); + return true; + } + + public String addClone(NBTTagCompound nbttagcompound, String name, String folderName) { + cleanTags(nbttagcompound); + saveClone(folderName, name, nbttagcompound); + return name; + } + + public String addClone(NBTTagCompound nbttagcompound, String name, String folderName, NBTTagCompound tempTags) { + cleanTagList(nbttagcompound, tempTags); + cleanTags(nbttagcompound); + saveClone(folderName, name, nbttagcompound); + return name; + } + + // ==================== Move Operations ==================== + + public boolean moveClone(String cloneName, int fromTab, String toFolder) { + NBTTagCompound data = getCloneData(null, cloneName, fromTab); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromTab(cloneName, fromTab); + + saveClone(toFolder, cloneName, data); + setTagUUIDsForFolder(cloneName, toFolder, tagUUIDs); + + removeClone(cloneName, fromTab); + return true; + } + + public boolean moveClone(String cloneName, String fromFolder, int toTab) { + NBTTagCompound data = getCloneData(null, cloneName, fromFolder); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromFolder(cloneName, fromFolder); + + saveClone(toTab, cloneName, data); + setTagUUIDsForTab(cloneName, toTab, tagUUIDs); + + removeClone(cloneName, fromFolder); + return true; + } + + public boolean moveClone(String cloneName, String fromFolder, String toFolder) { + NBTTagCompound data = getCloneData(null, cloneName, fromFolder); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromFolder(cloneName, fromFolder); + + saveClone(toFolder, cloneName, data); + setTagUUIDsForFolder(cloneName, toFolder, tagUUIDs); + + removeClone(cloneName, fromFolder); + return true; + } + + public boolean moveClone(String cloneName, int fromTab, int toTab) { + NBTTagCompound data = getCloneData(null, cloneName, fromTab); + if (data == null) return false; + + HashSet tagUUIDs = getTagUUIDsFromTab(cloneName, fromTab); + + saveClone(toTab, cloneName, data); + setTagUUIDsForTab(cloneName, toTab, tagUUIDs); + + removeClone(cloneName, fromTab); + return true; + } + + // ==================== Tag Utilities ==================== + public NBTTagCompound cleanTagList(NBTTagCompound nbttagcompound, NBTTagCompound tempTags) { HashSet tagUUIDs = new HashSet(); if (nbttagcompound.hasKey("TagUUIDs")) { @@ -243,6 +494,25 @@ public class ServerCloneController implements ICloneHandler { return true; } + public boolean addToTagMap(NBTTagCompound nbttagcompound, String name, String folderName) { + HashSet tagUUIDs = new HashSet<>(); + if (nbttagcompound.hasKey("TagUUIDs")) { + NBTTagList nbtTagList = nbttagcompound.getTagList("TagUUIDs", 8); + for (int i = 0; i < nbtTagList.tagCount(); i++) { + tagUUIDs.add(UUID.fromString(nbtTagList.getStringTagAt(i))); + } + } + + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + if (!tagUUIDs.isEmpty()) { + tagMap.putClone(name, tagUUIDs); + } else { + tagMap.removeClone(name); + } + ServerTagMapController.Instance.saveTagMap(tagMap); + return true; + } + public boolean removeFromTagMap(String name, int tab) { TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); if (tagMap.removeClone(name)) { @@ -252,6 +522,41 @@ public class ServerCloneController implements ICloneHandler { return false; } + public boolean removeFromTagMap(String name, String folderName) { + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + if (tagMap.removeClone(name)) { + ServerTagMapController.Instance.saveTagMap(tagMap); + return true; + } + return false; + } + + protected HashSet getTagUUIDsFromTab(String cloneName, int tab) { + TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + protected HashSet getTagUUIDsFromFolder(String cloneName, String folderName) { + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + HashSet uuids = tagMap.getUUIDs(cloneName); + return uuids != null ? new HashSet<>(uuids) : new HashSet<>(); + } + + protected void setTagUUIDsForTab(String cloneName, int tab, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ServerTagMapController.Instance.getTagMap(tab); + tagMap.putClone(cloneName, tagUUIDs); + ServerTagMapController.Instance.saveTagMap(tagMap); + } + + protected void setTagUUIDsForFolder(String cloneName, String folderName, HashSet tagUUIDs) { + if (tagUUIDs == null || tagUUIDs.isEmpty()) return; + TagMap tagMap = ServerTagMapController.Instance.getTagMap(folderName); + tagMap.putClone(cloneName, tagUUIDs); + ServerTagMapController.Instance.saveTagMap(tagMap); + } + public void cleanTags(NBTTagCompound nbttagcompound) { if (nbttagcompound.hasKey("ItemGiverId")) nbttagcompound.setInteger("ItemGiverId", 0); @@ -288,6 +593,8 @@ public class ServerCloneController implements ICloneHandler { } } + // ==================== API Methods (ICloneHandler) ==================== + public IEntity spawn(double x, double y, double z, int tab, String name, IWorld world, boolean ignoreProtection) { NBTTagCompound compound = this.getCloneData((ICommandSender) null, name, tab); if (compound == null) { @@ -327,7 +634,7 @@ public class ServerCloneController implements ICloneHandler { for (File file : dir.listFiles()) { if (file.getName().endsWith(".json")) { NBTTagCompound compound = NBTJsonUtil.LoadFile(file); - Instance.cleanTags(compound); + cleanTags(compound); Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); arrayList.add(entity == null ? null : NpcAPI.Instance().getIEntity(entity)); } @@ -343,7 +650,7 @@ public class ServerCloneController implements ICloneHandler { if (compound == null) { throw new CustomNPCsException("Unknown clone tab:" + tab + " name:" + name, new Object[0]); } else { - Instance.cleanTags(compound); + cleanTags(compound); Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); return entity == null ? null : NpcAPI.Instance().getIEntity(entity); } @@ -354,7 +661,6 @@ public class ServerCloneController implements ICloneHandler { return compound != null; } - public void set(int tab, String name, IEntity entity) { NBTTagCompound compound = new NBTTagCompound(); if (!entity.getMCEntity().writeMountToNBT(compound)) @@ -367,4 +673,85 @@ public class ServerCloneController implements ICloneHandler { public void remove(int tab, String name) { this.removeClone(name, tab); } + + // --- Folder API Methods --- + + public String[] getFolders() { + return getFolderNames().toArray(new String[0]); + } + + public IEntity spawn(double x, double y, double z, String folderName, String name, IWorld world, boolean ignoreProtection) { + NBTTagCompound compound = getCloneData(null, name, folderName); + if (compound == null) { + throw new CustomNPCsException("Unknown clone folder:" + folderName + " name:" + name, new Object[0]); + } + Entity entity; + if (!ignoreProtection) { + entity = NoppesUtilServer.spawnCloneWithProtection(compound, (int) x, (int) y, (int) z, world.getMCWorld()); + } else { + entity = NoppesUtilServer.spawnClone(compound, (int) x, (int) y, (int) z, world.getMCWorld()); + } + return entity == null ? null : NpcAPI.Instance().getIEntity(entity); + } + + public IEntity spawn(IPos pos, String folderName, String name, IWorld world, boolean ignoreProtection) { + return this.spawn(pos.getX(), pos.getY(), pos.getZ(), folderName, name, world, ignoreProtection); + } + + public IEntity spawn(double x, double y, double z, String folderName, String name, IWorld world) { + return spawn(x, y, z, folderName, name, world, true); + } + + public IEntity spawn(IPos pos, String folderName, String name, IWorld world) { + return this.spawn(pos.getX(), pos.getY(), pos.getZ(), folderName, name, world); + } + + public IEntity[] getFolder(String folderName, IWorld world) { + File dir = getFolderDir(folderName); + if (!dir.exists() || !dir.isDirectory() || dir.listFiles() == null) { + return new IEntity[]{}; + } + + ArrayList arrayList = new ArrayList<>(); + try { + for (File file : dir.listFiles()) { + if (file.getName().endsWith(".json")) { + NBTTagCompound compound = NBTJsonUtil.LoadFile(file); + cleanTags(compound); + Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); + arrayList.add(entity == null ? null : NpcAPI.Instance().getIEntity(entity)); + } + } + } catch (Exception ignored) { + } + return arrayList.toArray(new IEntity[]{}); + } + + public IEntity get(String folderName, String name, IWorld world) { + NBTTagCompound compound = getCloneData(null, name, folderName); + if (compound == null) { + throw new CustomNPCsException("Unknown clone folder:" + folderName + " name:" + name, new Object[0]); + } + cleanTags(compound); + Entity entity = EntityList.createEntityFromNBT(compound, world.getMCWorld()); + return entity == null ? null : NpcAPI.Instance().getIEntity(entity); + } + + public boolean has(String folderName, String name) { + NBTTagCompound compound = getCloneData(null, name, folderName); + return compound != null; + } + + public void set(String folderName, String name, IEntity entity) { + NBTTagCompound compound = new NBTTagCompound(); + if (!entity.getMCEntity().writeMountToNBT(compound)) + throw new CustomNPCsException("Cannot save dead entities", new Object[0]); + + this.cleanTags(compound); + this.saveClone(folderName, name, compound); + } + + public void remove(String folderName, String name) { + this.removeClone(name, folderName); + } } diff --git a/src/main/java/noppes/npcs/controllers/ServerTagMapController.java b/src/main/java/noppes/npcs/controllers/ServerTagMapController.java index 0221481e3..42ca6afeb 100644 --- a/src/main/java/noppes/npcs/controllers/ServerTagMapController.java +++ b/src/main/java/noppes/npcs/controllers/ServerTagMapController.java @@ -35,6 +35,13 @@ public class ServerTagMapController { return dir; } + public File getCloneFolderDir(String folderName) { + File dir = new File(getDir(), folderName); + if (!dir.exists()) + dir.mkdir(); + return dir; + } + public TagMap getTagMap(int tab) { this.tagMap = new TagMap(tab); try { @@ -65,9 +72,33 @@ public class ServerTagMapController { this.tagMap.readNBT(nbtCompound); } + public TagMap getTagMap(String folderName) { + this.tagMap = new TagMap(folderName); + try { + File file = new File(getCloneFolderDir(folderName), "___tagmap.dat"); + if (file.exists()) { + loadTagMapFile(file); + } + } catch (Exception e) { + try { + File file = new File(getCloneFolderDir(folderName), "___tagmap.dat_old"); + if (file.exists()) { + loadTagMapFile(file); + } + } catch (Exception ignored) { + } + } + return this.tagMap; + } + public void saveTagMap(TagMap tagMap) { try { - File saveDir = getCloneTabDir(tagMap.cloneTab); + File saveDir; + if (tagMap.cloneFolder != null) { + saveDir = getCloneFolderDir(tagMap.cloneFolder); + } else { + saveDir = getCloneTabDir(tagMap.cloneTab); + } File file = new File(saveDir, "___tagmap.dat_new"); File file1 = new File(saveDir, "___tagmap.dat_old"); File file2 = new File(saveDir, "___tagmap.dat"); diff --git a/src/main/java/noppes/npcs/controllers/data/CloneFolder.java b/src/main/java/noppes/npcs/controllers/data/CloneFolder.java new file mode 100644 index 000000000..d2d0c7bcf --- /dev/null +++ b/src/main/java/noppes/npcs/controllers/data/CloneFolder.java @@ -0,0 +1,61 @@ +package noppes.npcs.controllers.data; + +import net.minecraft.nbt.NBTTagCompound; + +public class CloneFolder { + public String name; + public long createdDate; + + public CloneFolder() { + this.name = ""; + this.createdDate = System.currentTimeMillis(); + } + + public CloneFolder(String name) { + this.name = name; + this.createdDate = System.currentTimeMillis(); + } + + public void readNBT(NBTTagCompound compound) { + name = compound.getString("Name"); + createdDate = compound.getLong("Created"); + } + + public NBTTagCompound writeNBT(NBTTagCompound compound) { + compound.setString("Name", name); + compound.setLong("Created", createdDate); + return compound; + } + + public static boolean isValidName(String name) { + if (name == null || name.isEmpty()) { + return false; + } + if (name.length() > 32) { + return false; + } + if (!name.equals(name.trim())) { + return false; + } + if (name.equals(".") || name.equals("..")) { + return false; + } + if (name.startsWith("___")) { + return false; + } + try { + Integer.parseInt(name); + return false; + } catch (NumberFormatException ignored) { + } + for (char c : name.toCharArray()) { + if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') { + return false; + } + if (c < 32) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/noppes/npcs/controllers/data/DataScript.java b/src/main/java/noppes/npcs/controllers/data/DataScript.java index 74806605f..b112bf470 100644 --- a/src/main/java/noppes/npcs/controllers/data/DataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/DataScript.java @@ -9,13 +9,13 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import net.minecraft.world.WorldServer; +import noppes.npcs.CustomNpcs; import noppes.npcs.EventHooks; import noppes.npcs.LogWriter; import noppes.npcs.NBTTags; import noppes.npcs.api.IWorld; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.config.ConfigDebug; -import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumScriptType; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptContainer; @@ -74,7 +74,7 @@ public class DataScript implements IScriptHandlerPacket { public void readFromNBT(NBTTagCompound compound) { scripts = readScript(compound.getTagList("ScriptsContainers", 10)); this.scriptLanguage = compound.getString("ScriptLanguage"); - if (!ScriptController.Instance.languages.containsKey(scriptLanguage)) { + if (scriptLanguage == null || scriptLanguage.isEmpty()) { if (!ScriptController.Instance.languages.isEmpty()) { this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0]; } else { @@ -209,7 +209,7 @@ public class DataScript implements IScriptHandlerPacket { } public boolean isEnabled() { - return enabled && ScriptController.HasStart && !npc.worldObj.isRemote && !scripts.isEmpty() && ConfigScript.ScriptingEnabled; + return enabled && ScriptController.HasStart && !npc.worldObj.isRemote && !scripts.isEmpty() && CustomNpcs.proxy.isScriptingEnabled(); } @Override diff --git a/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java b/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java index 1c6f09da7..f8c961db7 100644 --- a/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/ForgeDataScript.java @@ -12,8 +12,8 @@ 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.CustomNpcs; import noppes.npcs.EventHooks; -import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptContainer; import noppes.npcs.controllers.ScriptController; @@ -36,7 +36,7 @@ public class ForgeDataScript extends MultiScriptHandler { } public boolean isEnabled() { - return this.enabled && ConfigScript.GlobalForgeScripts && ScriptController.HasStart && this.scripts.size() > 0; + return this.enabled && CustomNpcs.proxy.isGlobalForgeScripts() && ScriptController.HasStart && this.scripts.size() > 0; } @Override diff --git a/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java b/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java index 805ae7c8d..4654ff68f 100644 --- a/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/GlobalNPCDataScript.java @@ -3,8 +3,8 @@ package noppes.npcs.controllers.data; import kamkeel.npcs.network.packets.request.script.GlobalNPCScriptPacket; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; +import noppes.npcs.CustomNpcs; import noppes.npcs.api.entity.ICustomNpc; -import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptController; import noppes.npcs.entity.EntityNPCInterface; @@ -28,7 +28,7 @@ public class GlobalNPCDataScript extends MultiScriptHandler { } public boolean isEnabled() { - return ConfigScript.GlobalNPCScripts && this.enabled && ScriptController.HasStart && this.scripts.size() > 0; + return CustomNpcs.proxy.isGlobalNPCScripts() && this.enabled && ScriptController.HasStart && this.scripts.size() > 0; } @Override diff --git a/src/main/java/noppes/npcs/controllers/data/MultiScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/MultiScriptHandler.java index d4b4c027b..699b0542d 100644 --- a/src/main/java/noppes/npcs/controllers/data/MultiScriptHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/MultiScriptHandler.java @@ -55,7 +55,7 @@ public abstract class MultiScriptHandler extends ScriptHandler implements IScrip * Normalize the language to a valid one if the current language is not available. */ protected void normalizeLanguage() { - if (!ScriptController.Instance.languages.containsKey(this.scriptLanguage)) { + if (this.scriptLanguage == null || this.scriptLanguage.isEmpty()) { if (!ScriptController.Instance.languages.isEmpty()) { this.scriptLanguage = (String) ScriptController.Instance.languages.keySet().toArray()[0]; } else { diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java index 45f9dfe44..6d265de27 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerAbilityData.java @@ -229,16 +229,37 @@ public class PlayerAbilityData implements IPlayerAbilityData { currentTarget = null; // Players don't have auto-targets ability.start(null); - // Spawn telegraph - spawnTelegraph(ability, player, null); - - // Play wind up sound and animation - playAbilitySound(player, ability.getWindUpSound()); - playAbilityAnimation(ability.getWindUpAnimation()); + if (ability.getPhase() == AbilityPhase.ACTIVE) { + // Windup was 0 — skip telegraph/windup and go straight to active + executeImmediate(ability, player); + } else { + // Normal windup flow + spawnTelegraph(ability, player, null); + playAbilitySound(player, ability.getWindUpSound()); + playAbilityAnimation(ability.getWindUpAnimation()); + } return true; } + /** + * Execute an ability immediately (no windup). + * Called when windUpTicks is 0. + */ + private void executeImmediate(Ability ability, EntityPlayer player) { + // Play active sound and animation + playAbilitySound(player, ability.getActiveSound()); + playAbilityAnimation(ability.getActiveAnimation()); + + // Call onExecute + ability.onExecute(player, currentTarget, player.worldObj); + + // Check if ability completed during onExecute + if (ability.getPhase() == AbilityPhase.IDLE) { + handleAbilityCompletion(player); + } + } + // ═══════════════════════════════════════════════════════════════════ // CLIENT SYNC // ═══════════════════════════════════════════════════════════════════ @@ -453,13 +474,29 @@ public class PlayerAbilityData implements IPlayerAbilityData { // ANIMATION // ═══════════════════════════════════════════════════════════════════ - private void playAbilityAnimation(Animation animation) { + public void playAbilityAnimation(Animation animation) { if (animation == null || AnimationController.Instance == null) return; playerData.animationData.setEnabled(true); playerData.animationData.setAnimation(animation); playerData.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)); + } + + public void playAbilityAnimation(String animation) { + if (animation.isEmpty()) return; + if (AnimationController.Instance == null) return; + if (AnimationController.Instance.get(animation, true) == null) return; + + playAbilityAnimation((Animation) AnimationController.Instance.get(animation, true)); + } + private void stopAbilityAnimation() { playerData.animationData.setAnimation(null); playerData.animationData.updateClient(); diff --git a/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java b/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java index 38d9e8447..95f8bcb8e 100644 --- a/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java +++ b/src/main/java/noppes/npcs/controllers/data/PlayerDataScript.java @@ -5,6 +5,7 @@ import kamkeel.npcs.network.packets.request.script.PlayerScriptPacket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; +import noppes.npcs.CustomNpcs; import noppes.npcs.EventHooks; import noppes.npcs.NBTTags; import noppes.npcs.api.entity.IPlayer; @@ -60,7 +61,7 @@ public class PlayerDataScript extends MultiScriptHandler { } public boolean isEnabled() { - return ConfigScript.GlobalPlayerScripts && ScriptController.Instance.playerScripts.enabled && ScriptController.HasStart && (this.player == null || !this.player.worldObj.isRemote); + return CustomNpcs.proxy.isGlobalPlayerScripts() && ScriptController.Instance.playerScripts.enabled && ScriptController.HasStart && (this.player == null || !this.player.worldObj.isRemote); } @Override diff --git a/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java index 684c9a45b..096f8f381 100644 --- a/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/ScriptHandler.java @@ -1,7 +1,7 @@ package noppes.npcs.controllers.data; import cpw.mods.fml.common.eventhandler.Event; -import noppes.npcs.config.ConfigScript; +import noppes.npcs.CustomNpcs; import noppes.npcs.controllers.ScriptController; import java.util.ArrayList; @@ -14,7 +14,7 @@ public abstract class ScriptHandler implements IScriptHandler { protected long lastInited = -1; protected boolean canRunScripts() { - return enabled && ScriptController.HasStart && ConfigScript.ScriptingEnabled && scripts != null && !scripts.isEmpty(); + return enabled && ScriptController.HasStart && CustomNpcs.proxy.isScriptingEnabled() && scripts != null && !scripts.isEmpty(); } @Override diff --git a/src/main/java/noppes/npcs/controllers/data/SingleScriptHandler.java b/src/main/java/noppes/npcs/controllers/data/SingleScriptHandler.java index 00c273bca..854e77941 100644 --- a/src/main/java/noppes/npcs/controllers/data/SingleScriptHandler.java +++ b/src/main/java/noppes/npcs/controllers/data/SingleScriptHandler.java @@ -5,7 +5,7 @@ import io.netty.buffer.ByteBuf; import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.Constants; -import noppes.npcs.config.ConfigScript; +import noppes.npcs.CustomNpcs; import noppes.npcs.controllers.ScriptController; import java.io.IOException; @@ -32,7 +32,7 @@ public abstract class SingleScriptHandler extends ScriptHandler { } protected boolean canRunScripts() { - return enabled && ScriptController.HasStart && ConfigScript.ScriptingEnabled && container != null; + return enabled && ScriptController.HasStart && CustomNpcs.proxy.isScriptingEnabled() && container != null; } @Override @@ -142,7 +142,7 @@ public abstract class SingleScriptHandler extends ScriptHandler { * Normalize the language to a valid one if the current language is not available. */ protected void normalizeLanguage() { - if (!ScriptController.Instance.languages.containsKey(this.getLanguage())) { + if (this.getLanguage() == null || this.getLanguage().isEmpty()) { if (!ScriptController.Instance.languages.isEmpty()) { this.setLanguage((String) ScriptController.Instance.languages.keySet().toArray()[0]); } else { diff --git a/src/main/java/noppes/npcs/controllers/data/TagMap.java b/src/main/java/noppes/npcs/controllers/data/TagMap.java index e4c0ad57f..2205d96fd 100644 --- a/src/main/java/noppes/npcs/controllers/data/TagMap.java +++ b/src/main/java/noppes/npcs/controllers/data/TagMap.java @@ -13,10 +13,18 @@ import java.util.UUID; public class TagMap { public int cloneTab; + public String cloneFolder; public HashMap> tagMap; public TagMap(int tab) { this.cloneTab = tab; + this.cloneFolder = null; + this.tagMap = new HashMap>(); + } + + public TagMap(String folder) { + this.cloneTab = -1; + this.cloneFolder = folder; this.tagMap = new HashMap>(); } diff --git a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java index 16389f74d..6e4b40884 100644 --- a/src/main/java/noppes/npcs/entity/EntityNPCInterface.java +++ b/src/main/java/noppes/npcs/entity/EntityNPCInterface.java @@ -308,6 +308,13 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti @Override public void onUpdate() { super.onUpdate(); + + // Re-apply locks after super.onUpdate() to override body rotation smoothing + // in EntityLivingBase.onUpdate() (func_110146_f) which runs AFTER onLivingUpdate() + // and overwrites renderYawOffset, causing a visible twitch each frame. + abilities.applyRotationControl(); + abilities.applyLockedPosition(); + if (!isRemote()) { if (this.ticksExisted % 10 == 0) { EventHooks.onNPCUpdate(this); @@ -481,8 +488,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti super.onLivingUpdate(); - // Apply locked rotation after super.onLivingUpdate() to override look helper changes - abilities.applyLockedRotation(); + // Apply locks after super.onLivingUpdate() to override AI/physics changes + abilities.applyRotationControl(); + abilities.applyLockedPosition(); handleMountRiderState(); @@ -670,6 +678,9 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti if (entity instanceof EntityLivingBase) attackingEntity = (EntityLivingBase) entity; + if (faction.isPassive) + return false; + if (attackingEntity != null && attackingEntity == getOwner()) return false; else if (attackingEntity instanceof EntityNPCInterface) { @@ -1693,7 +1704,7 @@ public abstract class EntityNPCInterface extends EntityCreature implements IEnti } /** - * 1: walking, 2:interacting, 4:attacking, 8:killed + * 1: walking, 2:interacting, 4:attacking, 8:killed, 16:rotationLocked */ public boolean getBoolFlag(int id) { return (dataWatcher.getWatchableObjectInt(15) & id) != 0; diff --git a/src/main/java/noppes/npcs/items/ItemElementalStaff.java b/src/main/java/noppes/npcs/items/ItemElementalStaff.java index d786222b1..03384f76a 100644 --- a/src/main/java/noppes/npcs/items/ItemElementalStaff.java +++ b/src/main/java/noppes/npcs/items/ItemElementalStaff.java @@ -16,6 +16,7 @@ public class ItemElementalStaff extends ItemStaff { public ItemElementalStaff(int par1, EnumNpcToolMaterial material) { super(par1, material); setHasSubtypes(true); + this.color = OrbColor.GENERIC; } @Override diff --git a/src/main/java/noppes/npcs/items/ItemStaff.java b/src/main/java/noppes/npcs/items/ItemStaff.java index 89ce879cf..2a54c49a3 100644 --- a/src/main/java/noppes/npcs/items/ItemStaff.java +++ b/src/main/java/noppes/npcs/items/ItemStaff.java @@ -1,32 +1,39 @@ package noppes.npcs.items; +import kamkeel.npcs.controllers.data.ability.AnchorPoint; +import kamkeel.npcs.controllers.data.ability.data.*; +import kamkeel.npcs.entity.EntityAbilityOrb; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; -import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import noppes.npcs.CustomItems; import noppes.npcs.CustomNpcs; import noppes.npcs.constants.EnumNpcToolMaterial; import noppes.npcs.enchants.EnchantInterface; -import noppes.npcs.entity.EntityMagicProjectile; import noppes.npcs.entity.EntityProjectile; import noppes.npcs.util.IProjectileCallback; import org.lwjgl.opengl.GL11; +import java.awt.*; + public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { private EnumNpcToolMaterial material; + protected OrbColor color; + public ItemStaff(int par1, EnumNpcToolMaterial material) { super(par1); this.material = material; + this.color = OrbColor.get(material.ordinal());; setCreativeTab(CustomItems.tabWeapon); } @@ -36,70 +43,93 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { } @Override - public void onPlayerStoppedUsing(ItemStack stack, World worldObj, EntityPlayer player, int par4) { - if (worldObj.isRemote) { + public void onPlayerStoppedUsing(ItemStack stack, World world, EntityPlayer player, int par4) { + + if (world.isRemote) return; - } + if (stack.stackTagCompound == null) return; - Entity entity = ((WorldServer) player.worldObj).getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); - if (entity == null || !(entity instanceof EntityProjectile)) + + Entity entity = ((WorldServer) world) + .getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); + + if (!(entity instanceof EntityAbilityOrb)) return; - EntityProjectile item = (EntityProjectile) entity; - item.callback = this; - item.callbackItem = stack; - item.explosive = true; - item.explosiveDamage = false; - item.explosiveRadius = 1; - item.prevRotationYaw = item.rotationYaw = player.rotationYaw; - item.prevRotationPitch = item.rotationPitch = player.rotationPitch; - item.shoot(2); - player.worldObj.playSoundAtEntity(player, "customnpcs:magic.shot", 1.0F, 1); + EntityAbilityOrb orb = (EntityAbilityOrb) entity; + orb.startMoving(null); + + world.playSoundAtEntity( + player, + "customnpcs:magic.shot", + 1.0F, + 1.0F + ); } @Override public void onUsingTick(ItemStack stack, EntityPlayer player, int count) { int tick = getMaxItemUseDuration(stack) - count; + if (player.worldObj.isRemote) { spawnParticle(stack, player); return; } + int chargeTime = 20 + material.getHarvestLevel() * 8; + if (tick == chargeTime) { + if (!player.capabilities.isCreativeMode && !hasInfinite(stack)) { if (!hasItem(player, CustomItems.mana)) return; consumeItem(player, CustomItems.mana); } - player.worldObj.playSoundAtEntity(player, "customnpcs:magic.charge", 1.0F, 1); + + player.worldObj.playSoundAtEntity( + player, + "customnpcs:magic.charge", + 1.0F, + 1.0F + ); + if (stack.stackTagCompound == null) { stack.stackTagCompound = new NBTTagCompound(); } + int damage = 6 + material.getDamageVsEntity() + player.worldObj.rand.nextInt(4); damage += damage * EnchantInterface.getLevel(EnchantInterface.Damage, stack) * 0.5f; - EntityProjectile projectile = new EntityMagicProjectile(player.worldObj, player, getProjectile(stack), false); - projectile.damage = damage; - projectile.setSpeed(25); - double dx = -MathHelper.sin((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - double dz = MathHelper.cos((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - projectile.setPosition(player.posX + dx * 0.8, player.posY + 1.5 - player.rotationPitch / 80, player.posZ + dz * 0.8); - player.worldObj.spawnEntityInWorld(projectile); - stack.stackTagCompound.setInteger("MagicProjectile", projectile.getEntityId());//entityid - } - if (tick > chargeTime && stack.stackTagCompound != null) { - Entity entity = ((WorldServer) player.worldObj).getEntityByID(stack.stackTagCompound.getInteger("MagicProjectile")); - if (entity == null || !(entity instanceof EntityProjectile)) - return; - EntityProjectile item = (EntityProjectile) entity; - item.ticksInAir = 0; - double dx = -MathHelper.sin((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - double dz = MathHelper.cos((float) ((player.rotationYaw / 180F) * Math.PI)) * MathHelper.cos((float) ((player.rotationPitch / 180F) * Math.PI)); - item.setPosition(player.posX + dx * 0.8, player.posY + 1.5 - player.rotationPitch / 80, player.posZ + dz * 0.8); - } + EnergyCombatData combat = new EnergyCombatData(); + combat.damage = damage; + combat.explosive = true; + EnergyDisplayData colorData = new EnergyDisplayData(getOrbColor(stack, false), getOrbColor(stack, true)); + EnergyLightningData lightning = new EnergyLightningData(); + EnergyLifespanData lifespan = new EnergyLifespanData(100, 72000); + EnergyHomingData homing = new EnergyHomingData(); + EnergyTrajectoryData trajectory = new EnergyTrajectoryData(); + + homing.speed = 0.5f; + homing.homingStrength = 0.35f; + homing.homingRange = 20f; + + EntityAbilityOrb orb = new EntityAbilityOrb( + player.worldObj, player, null, + player.posX, player.posY + player.getEyeHeight(), player.posZ, + 1.0f, colorData, combat, homing, lightning, lifespan, trajectory + ); + + orb.setupCharging( + new EnergyAnchorData(AnchorPoint.FRONT, 0, -1, 0), + chargeTime + ); + + player.worldObj.spawnEntityInWorld(orb); + stack.stackTagCompound.setInteger("MagicProjectile", orb.getEntityId()); + } } @Override @@ -118,6 +148,15 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { return EnumAction.bow; } + public int getOrbColor(ItemStack stack, boolean outer) { + if (color == OrbColor.GENERIC) { + float[] color = EntitySheep.fleeceColorTable[stack.getItemDamage()]; + return new Color(color[0], color[1], color[2]).getRGB(); + } + + return outer ? color.outer : color.inner; + } + public ItemStack getProjectile(ItemStack stack) { if (stack.getItem() == CustomItems.staffWood) { return new ItemStack(CustomItems.spellNature); @@ -196,4 +235,32 @@ public class ItemStaff extends ItemNpcInterface implements IProjectileCallback { public boolean hasInfinite(ItemStack stack) { return EnchantInterface.getLevel(EnchantInterface.Infinite, stack) > 0; } + + public enum OrbColor { + WOOD(0x7cc818, 0x644a32), + STONE(0x532d5b, 0x515151), + BRONZE(0x83F7F6, 0x5CF0FF), + IRON(0xf7fac5, 0xeafa94), + DIA(0x44B6FF, 0x94DFED), + GOLD(0xb3011e, 0xd47c32), + EMERALD(0xdd6df7, 0xcf1dfa), + DEMONIC(0xb8144a, 0x422643), + FROST(0xffffff, 0xaccbfe), + MITHRIL(0xf7fac5, 0xffffff), + GENERIC(0xFFFFFF, 0x88FFFF); + + public final int inner; + public final int outer; + + OrbColor(int inner, int outer) { + this.inner = inner; + this.outer = outer; + } + + public static OrbColor get(int id) { + if (id >= OrbColor.values().length || id < 0) return GENERIC; + + return OrbColor.values()[id]; + } + } } diff --git a/src/main/java/noppes/npcs/janino/JaninoScript.java b/src/main/java/noppes/npcs/janino/JaninoScript.java index 1800cc895..2afe8052f 100644 --- a/src/main/java/noppes/npcs/janino/JaninoScript.java +++ b/src/main/java/noppes/npcs/janino/JaninoScript.java @@ -7,7 +7,6 @@ import net.minecraft.nbt.NBTTagCompound; import noppes.npcs.CustomNpcs; import noppes.npcs.NBTTags; import noppes.npcs.api.handler.IHookDefinition; -import noppes.npcs.config.ConfigScript; import noppes.npcs.constants.EnumScriptType; import noppes.npcs.constants.ScriptContext; import noppes.npcs.controllers.ScriptController; @@ -160,9 +159,9 @@ public abstract class JaninoScript implements IScriptUnit { private String getFullCode() { StringBuilder sb = new StringBuilder(); - if (ConfigScript.RunLoadedScriptsFirst) appendExternalScripts(sb); + if (CustomNpcs.proxy.isRunLoadedScriptsFirst()) appendExternalScripts(sb); if (script != null && !script.isEmpty()) sb.append(script).append("\n"); - if (!ConfigScript.RunLoadedScriptsFirst) appendExternalScripts(sb); + if (!CustomNpcs.proxy.isRunLoadedScriptsFirst()) appendExternalScripts(sb); return sb.toString(); } diff --git a/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java b/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java index c997729ca..9b09759c0 100644 --- a/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java +++ b/src/main/java/noppes/npcs/mixin/CustomNPCsMixinPlugin.java @@ -56,7 +56,6 @@ public class CustomNPCsMixinPlugin implements IMixinConfigPlugin { } mixins.add("MixinItemStack"); - mixins.add("MixinItem"); } return mixins; } diff --git a/src/main/java/noppes/npcs/mixin/MixinItem.java b/src/main/java/noppes/npcs/mixin/MixinItem.java deleted file mode 100644 index 7f2156919..000000000 --- a/src/main/java/noppes/npcs/mixin/MixinItem.java +++ /dev/null @@ -1,27 +0,0 @@ -package noppes.npcs.mixin; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import noppes.npcs.client.gui.player.AuctionTooltipHandler; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; - -/** - * Mixin to inject auction information into item tooltips when viewing auction GUIs. - */ -@Mixin(Item.class) -public class MixinItem { - - @SideOnly(Side.CLIENT) - @Inject(method = "addInformation", at = @At("HEAD")) - public void onAddInformation(ItemStack stack, EntityPlayer player, List tooltip, boolean advanced, CallbackInfo ci) { - AuctionTooltipHandler.addAuctionInfo(stack, tooltip); - } -} diff --git a/src/main/java/noppes/npcs/mixin/MixinItemStack.java b/src/main/java/noppes/npcs/mixin/MixinItemStack.java index 054269e23..8615573c0 100644 --- a/src/main/java/noppes/npcs/mixin/MixinItemStack.java +++ b/src/main/java/noppes/npcs/mixin/MixinItemStack.java @@ -1,20 +1,9 @@ package noppes.npcs.mixin; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import kamkeel.npcs.util.AttributeItemUtil; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.StatCollector; -import noppes.npcs.client.gui.player.GuiAuctionInterface; -import noppes.npcs.client.gui.player.GuiAuctionListing; -import noppes.npcs.config.ConfigMarket; -import noppes.npcs.containers.ContainerAuctionListing; -import noppes.npcs.controllers.data.AuctionListing; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/noppes/npcs/scripted/constants/EntityType.java b/src/main/java/noppes/npcs/scripted/constants/EntityType.java index bfe576856..995969682 100644 --- a/src/main/java/noppes/npcs/scripted/constants/EntityType.java +++ b/src/main/java/noppes/npcs/scripted/constants/EntityType.java @@ -14,4 +14,5 @@ public class EntityType { public static final int ARROW = 10; public static final int THROWABLE = 11; public static final int FISH_HOOK = 12; + public static final int ENERGY_PROJECTILE = 13; } diff --git a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java index 26f7a1ba7..f534f9dbc 100644 --- a/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java +++ b/src/main/java/noppes/npcs/scripted/entity/ScriptNpc.java @@ -5,6 +5,7 @@ import net.minecraft.item.ItemStack; import noppes.npcs.NoppesUtilServer; import noppes.npcs.api.IPos; import noppes.npcs.api.ITimers; +import noppes.npcs.api.ability.IDataAbilities; import noppes.npcs.api.entity.ICustomNpc; import noppes.npcs.api.entity.IEntityLivingBase; import noppes.npcs.api.entity.IPlayer; @@ -51,6 +52,7 @@ import noppes.npcs.scripted.roles.ScriptRoleInterface; import noppes.npcs.scripted.roles.ScriptRoleMailman; import noppes.npcs.scripted.roles.ScriptRoleTrader; import noppes.npcs.scripted.roles.ScriptRoleTransporter; +import noppes.npcs.scripted.wrapper.ScriptDataAbilities; import noppes.npcs.util.ValueUtil; import java.util.ArrayList; @@ -1458,7 +1460,7 @@ public class ScriptNpc extends ScriptLiving imp return npc.stats.magicData; } - public noppes.npcs.api.ability.IDataAbilities getAbilityData() { - return new noppes.npcs.scripted.wrapper.ScriptDataAbilities(npc); + public IDataAbilities getAbilityData() { + return new ScriptDataAbilities(npc); } } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java index d0b5259ea..e27f6e075 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptDataAbilities.java @@ -42,12 +42,25 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public void addAbility(IAbility ability) { if (ability instanceof Ability) { - data.addAbility((Ability) ability); + Ability a = (Ability) ability; + // Validate ability allows NPCs + if (!a.getAllowedBy().allowsNpc()) { + return; // Ability is PLAYER_ONLY + } + data.addAbility(a); } } @Override public void addAbilityReference(String key) { + // Validate ability exists and allows NPCs + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsNpc()) { + return; // Ability is PLAYER_ONLY + } data.addAbilityReference(key); } @@ -158,6 +171,14 @@ public class ScriptDataAbilities implements IDataAbilities { @Override public boolean executeAbility(String key, Object target) { + // Validate ability exists and allows NPCs + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return false; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsNpc()) { + return false; // Ability is PLAYER_ONLY + } EntityLivingBase targetEntity = resolveTarget(target); return data.executeAbility(key, targetEntity); } diff --git a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java index a36c65d51..42ed3372e 100644 --- a/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java +++ b/src/main/java/noppes/npcs/scripted/wrapper/ScriptPlayerAbilityData.java @@ -1,5 +1,7 @@ package noppes.npcs.scripted.wrapper; +import kamkeel.npcs.controllers.data.ability.Ability; +import kamkeel.npcs.controllers.data.ability.AbilityController; import net.minecraft.entity.player.EntityPlayer; import noppes.npcs.api.ability.IAbility; import noppes.npcs.api.ability.IPlayerAbilityData; @@ -26,7 +28,17 @@ public class ScriptPlayerAbilityData implements IPlayerAbilityData { @Override public void unlockAbility(String key) { - data.unlockAbility(key); + // Validate ability exists and allows players + Ability ability = AbilityController.Instance.resolveAbility(key); + if (ability == null) { + return; // Ability doesn't exist + } + if (!ability.getAllowedBy().allowsPlayer()) { + return; // Ability is NPC-only + } + // Use canonical key (registry key for built-in, UUID for custom) + String canonicalKey = ability.getId() != null ? ability.getId() : key; + data.unlockAbility(canonicalKey); } @Override diff --git a/src/main/java/somehussar/gui/AnnotatedGui.java b/src/main/java/somehussar/gui/AnnotatedGui.java new file mode 100644 index 000000000..8cdf224d5 --- /dev/null +++ b/src/main/java/somehussar/gui/AnnotatedGui.java @@ -0,0 +1,44 @@ +package somehussar.gui; + +import net.minecraft.client.gui.GuiScreen; +import noppes.npcs.client.gui.util.GuiNpcLabel; +import noppes.npcs.client.gui.util.SubGuiInterface; +import somehussar.gui.annotationHandling.GuiFieldHandler; +import somehussar.gui.annotationHandling.field.EditableField; + +public class AnnotatedGui extends SubGuiInterface { + private final GuiFieldHandler.ClassMetadata metadata; + + public AnnotatedGui(T object, String[] groups, GuiScreen parent) { + this(object, groups, parent, 256, 216); + } + + public AnnotatedGui(T object, String[] groups, GuiScreen parent, int xSize, int ySize) { + if (object != null) + metadata = GuiFieldHandler.getMetadata(object.getClass()); + else + metadata = null; + setBackground("menubg.png"); + this.xSize = xSize; + this.ySize = ySize; + closeOnEsc = true; + this.parent = parent; + } + + @Override + public void initGui() { + super.initGui(); + if (metadata == null) + return; + + int i = 0; + for (EditableField field : metadata.getParent().getDeclaredFields()) { + addLabel(new GuiNpcLabel(i++, field.getName(), guiLeft+8, guiTop+i*15+5)); + } + } + + @Override + public void save() { + + } +} diff --git a/src/main/java/somehussar/gui/ImmediateTextField.java b/src/main/java/somehussar/gui/ImmediateTextField.java new file mode 100644 index 000000000..5f49a9d84 --- /dev/null +++ b/src/main/java/somehussar/gui/ImmediateTextField.java @@ -0,0 +1,32 @@ +package somehussar.gui; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import noppes.npcs.client.gui.util.GuiNpcTextField; +import somehussar.gui.annotationHandling.field.EditableField; + +public class ImmediateTextField extends GuiNpcTextField{ + private final EditableField editableField; +// +// private final GuiNpcTextField encapsulatedField; + + public ImmediateTextField(int id, EditableField field, int xPos, int yPos) { + this(id, field, Minecraft.getMinecraft().fontRenderer, xPos, yPos); + } + public ImmediateTextField(int id, EditableField field, FontRenderer fontRenderer, int xPos, int yPos) { + super(id, null, fontRenderer, xPos, yPos, 0, 0, null); + + this.editableField = field; + } + + @Override + public void drawTextBox(int mousX, int mousY) { + + } + + @Override + public void mouseClicked(int xPos, int yPos, int k) { + xPos -= this.xPosition; + yPos -= this.yPosition; + } +} diff --git a/src/main/java/somehussar/gui/annotationHandling/FieldConstraint.java b/src/main/java/somehussar/gui/annotationHandling/FieldConstraint.java new file mode 100644 index 000000000..7a9b124e4 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/FieldConstraint.java @@ -0,0 +1,5 @@ +package somehussar.gui.annotationHandling; + +public interface FieldConstraint { + void validate(Object value); +} diff --git a/src/main/java/somehussar/gui/annotationHandling/FieldConstraints.java b/src/main/java/somehussar/gui/annotationHandling/FieldConstraints.java new file mode 100644 index 000000000..9a48fd1e3 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/FieldConstraints.java @@ -0,0 +1,27 @@ +package somehussar.gui.annotationHandling; + +public final class FieldConstraints { + + private static final FieldConstraints EMPTY = + new FieldConstraints(new FieldConstraint[0]); + + private final FieldConstraint[] constraints; + + public FieldConstraints(FieldConstraint[] constraints) { + this.constraints = constraints; + } + + public static FieldConstraints empty() { + return EMPTY; + } + + public void validate(Object value) { + for (FieldConstraint c : constraints) { + c.validate(value); + } + } + + public boolean isEmpty() { + return constraints.length == 0; + } +} diff --git a/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java b/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java new file mode 100644 index 000000000..596f3ab2f --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/GuiEditable.java @@ -0,0 +1,46 @@ +package somehussar.gui.annotationHandling; + +import java.lang.annotation.Annotation; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface GuiEditable { + + @Retention(RetentionPolicy.RUNTIME) + @interface Field { + String value(); + + /** + * Display order + * Higher value = higher priority. + */ + int order() default 0; + + } + + @Retention(RetentionPolicy.RUNTIME) + @interface Group { + String value(); + } + + @Retention(RetentionPolicy.RUNTIME) + @interface Size { + int labelWidth() default 60; + int fieldWidth() default 50; + + GuiEditable.Size DEFAULT_SIZE = new GuiEditable.Size() { + @Override + public int labelWidth() { + return 60; + } + + @Override + public int fieldWidth() { + return 50; + } + @Override public Class annotationType() { return GuiEditable.Size.class; } + }; + + } +} diff --git a/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java b/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java new file mode 100644 index 000000000..c6b7f3625 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/GuiFieldHandler.java @@ -0,0 +1,140 @@ +package somehussar.gui.annotationHandling; + +import somehussar.gui.annotationHandling.constraints.ConstraintFactory; +import somehussar.gui.annotationHandling.constraints.NumericConstraint; +import somehussar.gui.annotationHandling.constraints.NumericConstraintFactory; +import somehussar.gui.annotationHandling.field.EditableField; + +import java.lang.annotation.Annotation; +import java.lang.invoke.MethodHandles; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class GuiFieldHandler { + + private static final Map, ClassMetadata> CACHE = new HashMap<>(); + private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup(); + + public static final Map, ConstraintFactory> registry = new HashMap<>(); + + static { + registry.put(NumericConstraint.class, new NumericConstraintFactory()); + } + + + private GuiFieldHandler() {} + + public static ClassMetadata getMetadata(Class type) { + return CACHE.computeIfAbsent(type, GuiFieldHandler::scanClass); + } + + @SuppressWarnings({"RawUseOfParameterized"}) + private static ClassMetadata scanClass(Class type) { + if (!type.isAnnotationPresent(GuiEditable.class)) { + return null; + } + + ClassMetadata parent = null; + + Class superCls = type.getSuperclass(); + if (superCls != null && superCls != Object.class) { + parent = getMetadata(superCls); + } + + List list = new ArrayList<>(); + for (Field field : type.getDeclaredFields()) { + EditableField editableField = createEditableField(field); + + if (editableField != null) { + list.add(editableField); + } + } + + return new ClassMetadata( + type, + list.toArray(list.toArray(new EditableField[0])), + parent + ); + } + + @SuppressWarnings({"RawUseOfParameterized", "unchecked"}) + private static EditableField createEditableField(Field field) { + try { + GuiEditable.Field fieldConfig = field.getAnnotation(GuiEditable.Field.class); + if (fieldConfig == null) return null; + if (Modifier.isFinal(field.getModifiers())) return null; + + GuiEditable.Size size = field.getAnnotation(GuiEditable.Size.class); + if (size == null) size = GuiEditable.Size.DEFAULT_SIZE;; + + field.setAccessible(true); + EditableField.Builder builder = new EditableField.Builder() + .name(fieldConfig.value()) + .type(field.getType()) + .getter(LOOKUP.unreflectGetter(field)) + .setter(LOOKUP.unreflectSetter(field)) + .constraints(buildConstraints(field)) + .order(fieldConfig.order()) + .size(size); + + + GuiEditable.Group group = field.getAnnotation(GuiEditable.Group.class); + if (group != null) + builder.group(group.value()); + + + return builder.build(); + } catch (IllegalAccessException e) { + throw new RuntimeException( + "Failed to bind field: " + field, e); + } + } + + @SuppressWarnings({"RawUseOfParameterized", "unchecked"}) + private static FieldConstraints buildConstraints(Field field) { + List list = new ArrayList<>(); + + for (Annotation ann : field.getAnnotations()) { + ConstraintFactory factory = registry.get(ann.annotationType()); + if (factory != null) { + FieldConstraint c = factory.create(field, ann); + list.add(c); + } + } + + if (list.isEmpty()) return FieldConstraints.empty(); + return new FieldConstraints(list.toArray(new FieldConstraint[0])); + } + + + @SuppressWarnings({"RawUseOfParameterized"}) + public static final class ClassMetadata { + final Class type; + final EditableField[] fields; // only declared fields + final ClassMetadata parent; // superclass metadata (nullable) + + ClassMetadata(Class type, EditableField[] fields, ClassMetadata parent) { + this.type = type; + this.fields = fields; + this.parent = parent; + } + + public ClassMetadata getParent() { + return parent; + } + + public EditableField[] getDeclaredFields() { + return fields; + } + + public Class getType() { + return type; + } + } + + +} diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/ConstraintFactory.java b/src/main/java/somehussar/gui/annotationHandling/constraints/ConstraintFactory.java new file mode 100644 index 000000000..d62de94b4 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/ConstraintFactory.java @@ -0,0 +1,10 @@ +package somehussar.gui.annotationHandling.constraints; + +import somehussar.gui.annotationHandling.FieldConstraint; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; + +public interface ConstraintFactory { + FieldConstraint create(Field field, A annotation); +} diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java new file mode 100644 index 000000000..3b9268a30 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraint.java @@ -0,0 +1,13 @@ +package somehussar.gui.annotationHandling.constraints; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(value = RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface NumericConstraint { + double min() default Double.NEGATIVE_INFINITY; + double max() default Double.POSITIVE_INFINITY; +} diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraintFactory.java b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraintFactory.java new file mode 100644 index 000000000..24b08ceb9 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericConstraintFactory.java @@ -0,0 +1,13 @@ +package somehussar.gui.annotationHandling.constraints; + +import somehussar.gui.annotationHandling.FieldConstraint; + +import java.lang.reflect.Field; + +public class NumericConstraintFactory implements ConstraintFactory { + + @Override + public FieldConstraint create(Field field, NumericConstraint ann) { + return new NumericRangeConstraint(ann.min(), ann.max()); + } +} diff --git a/src/main/java/somehussar/gui/annotationHandling/constraints/NumericRangeConstraint.java b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericRangeConstraint.java new file mode 100644 index 000000000..198888d25 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/constraints/NumericRangeConstraint.java @@ -0,0 +1,35 @@ +package somehussar.gui.annotationHandling.constraints; + +import somehussar.gui.annotationHandling.FieldConstraint; + +public final class NumericRangeConstraint implements FieldConstraint { + + private final double min; + private final double max; + + public NumericRangeConstraint(double min, double max) { + this.min = min; + this.max = max; + } + + @Override + public void validate(Object value) { + if (!(value instanceof Number)) { + throw new ConstraintViolationException("Expected number, got " + value); + } + + double v = ((Number) value).doubleValue(); + if (v < min || v > max) { + throw new ConstraintViolationException( + "Value " + v + " must be between " + min + " and " + max + ); + } + } + + public static final class ConstraintViolationException extends RuntimeException { + public ConstraintViolationException(String message) { + super(message); + } + } + +} diff --git a/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java b/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java new file mode 100644 index 000000000..73172ef42 --- /dev/null +++ b/src/main/java/somehussar/gui/annotationHandling/field/EditableField.java @@ -0,0 +1,85 @@ +package somehussar.gui.annotationHandling.field; + +import somehussar.gui.annotationHandling.FieldConstraints; +import somehussar.gui.annotationHandling.GuiEditable; + +import java.lang.invoke.MethodHandle; + +public final class EditableField { + + private final String name; + private final Class type; + private final MethodHandle getter; + private final MethodHandle setter; + private final FieldConstraints constraints; + private final int order; + private final String group; + private final GuiEditable.Size size; + + public String getName() { + return name; + } + + public Class getType() { + return type; + } + + @SuppressWarnings({"unchecked"}) + public T read(T instance) { + try { + return (T) getter.invoke(instance); + } catch (Throwable t) { + throw new RuntimeException("Failed to read field " + name, t); + } + } + + public void write(T instance, T value) { + constraints.validate(value); + try { + setter.invoke(instance, value); + } catch (Throwable t) { + throw new RuntimeException("Failed to write field " + name, t); + } + } + + public FieldConstraints getConstraints() { + return this.constraints; + } + + public int getOrder() { return this.order; } + + EditableField(Builder b) { + this.name = b.name; + this.type = b.type; + this.getter = b.getter; + this.setter = b.setter; + this.constraints = b.constraints; + this.order = b.order; + this.group = b.group; + this.size = b.size; + } + + public static class Builder { + private String name; + private Class type; + private MethodHandle getter; + private MethodHandle setter; + private FieldConstraints constraints; + private int order; + private String group = null; + private GuiEditable.Size size; + + public Builder name(String v) { this.name = v; return this; } + public Builder type(Class v) { this.type = v; return this; } + public Builder getter(MethodHandle v) { this.getter = v; return this; } + public Builder setter(MethodHandle v) { this.setter = v; return this; } + public Builder constraints(FieldConstraints v) { this.constraints = v; return this; } + public Builder order(int order) { this.order = order; return this; } + public Builder group(String value) { this.group = value; return this; } + public Builder size(GuiEditable.Size size) { this.size = size; return this; } + + public EditableField build() { + return new EditableField<>(this); + } + } +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DualBeam_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Active.json similarity index 99% rename from src/main/resources/assets/customnpcs/animations/Ability_DualBeam_Active.json rename to src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Active.json index fa47349f9..c98f89236 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_DualBeam_Active.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Active.json @@ -198,6 +198,6 @@ "ID": 12, "WhileAttacking": 1b, "WhileWalking": 1b, - "Name": "Ability_DualBeam_Active", + "Name": "Ability_BeamDual_Active", "WhileStanding": 1b } diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DualBeam_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json similarity index 99% rename from src/main/resources/assets/customnpcs/animations/Ability_DualBeam_Windup.json rename to src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json index 99437fc2d..d793e3f22 100644 --- a/src/main/resources/assets/customnpcs/animations/Ability_DualBeam_Windup.json +++ b/src/main/resources/assets/customnpcs/animations/Ability_BeamDual_Windup.json @@ -196,6 +196,6 @@ "ID": 11, "WhileAttacking": 1b, "WhileWalking": 1b, - "Name": "Ability_DualBeam_Windup", + "Name": "Ability_BeamDual_Windup", "WhileStanding": 1b } diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Active.json new file mode 100644 index 000000000..1fdf06c24 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Active.json @@ -0,0 +1,86 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 18.0f, + "Rotation0": 88.0f, + "Pivot0": -10.0f, + "Pivot1": 0.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 6.0f, + "Rotation0": 82.0f, + "Pivot0": 3.0f, + "Pivot1": 3.0f, + "Rotation2": 88.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_LEG", + "Rotation1": 107.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 56.0f, + "Rotation0": 0.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 20 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 14, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Cutter_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json new file mode 100644 index 000000000..153d90f12 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Cutter_Windup.json @@ -0,0 +1,156 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 1.0f, + "Part": "LEFT_ARM", + "Rotation1": -31.0f, + "Rotation0": -94.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": -3.0f, + "Part": "HEAD", + "Rotation1": -31.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": -75.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": -50.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 88.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 18.0f, + "Rotation0": 12.0f, + "Pivot0": -3.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Duration": 20 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 18.0f, + "Rotation0": 88.0f, + "Pivot0": -10.0f, + "Pivot1": 0.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 107.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 6.0f, + "Rotation0": 82.0f, + "Pivot0": 3.0f, + "Pivot1": 3.0f, + "Rotation2": 88.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_LEG", + "Rotation1": 107.0f, + "Rotation0": 6.0f, + "Pivot0": -2.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 56.0f, + "Rotation0": 0.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 13, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Cutter_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json new file mode 100644 index 000000000..8fbaa73da --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Active.json @@ -0,0 +1,392 @@ +{ + "Loop": 5, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": -37.0f, + "Rotation0": 37.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 56.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -37.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -25.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 120.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.5f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": -37.0f, + "Rotation0": 37.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 56.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -37.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -25.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 120.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": -37.0f, + "Rotation0": 37.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 56.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -37.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -25.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 120.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 75.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 75.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 2.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -145.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 75.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_ARM", + "Rotation1": 37.0f, + "Rotation0": -90.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": -12.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": 2.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 18, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_DiscDual_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json new file mode 100644 index 000000000..080306c95 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_DiscDual_Windup.json @@ -0,0 +1,293 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": -8.0f, + "Part": "BODY", + "Rotation1": 25.0f, + "Rotation0": 31.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": -8.0f, + "Part": "LEFT_ARM", + "Rotation1": 31.0f, + "Rotation0": -56.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_LEG", + "Rotation1": 25.0f, + "Rotation0": 18.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 360.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -8.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": -12.0f + } + ], + "Smooth": 0b, + "Duration": 10 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.35f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 170.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -107.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 50.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": -4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 360.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 46 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": 170.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -107.0f, + "Pivot0": -6.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -6.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 50.0f, + "Rotation0": 18.0f, + "Pivot0": -3.0f, + "Pivot1": -4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "FULL_MODEL", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 2b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "BODY", + "Rotation1": -37.0f, + "Rotation0": 37.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 56.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -37.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -25.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 0.0f, + "Rotation0": 120.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": -18.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 18.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 1, + "Smooth": 0b, + "ID": 17, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_DiscDual_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Guard_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Active.json new file mode 100644 index 000000000..258320341 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Active.json @@ -0,0 +1,50 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": -120.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 80.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 10 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 18, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Guard_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json new file mode 100644 index 000000000..9194dfd72 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Guard_Counter.json @@ -0,0 +1,203 @@ +{ + "Loop": 2, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": -120.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 80.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 60.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -60.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": -3.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -3.0f, + "Part": "RIGHT_ARM", + "Rotation1": -20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 60.0f + }, + { + "Pivot2": -3.0f, + "Part": "LEFT_ARM", + "Rotation1": 20.0f, + "Rotation0": 90.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": -60.0f + }, + { + "Pivot2": -6.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 25.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 31.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 10 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 17, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Guard_Counter", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json new file mode 100644 index 000000000..fa6b44543 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Active.json @@ -0,0 +1,77 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": -25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 6.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -63.0f, + "Rotation0": -31.0f, + "Pivot0": -2.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 20 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 19, + "Smooth": 0b, + "ID": 16, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_HeavyHit_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json new file mode 100644 index 000000000..15d49bce6 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_HeavyHit_Windup.json @@ -0,0 +1,1274 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.8f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 31.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 6.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -37.0f, + "Rotation0": -37.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 6.0f + } + ], + "Smooth": 0b, + "Duration": 10 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.1f, + "FrameParts": [ + { + "Pivot2": 3.0f, + "Part": "RIGHT_ARM", + "Rotation1": 40.0f, + "Rotation0": -107.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": -37.0f + }, + { + "Pivot2": -4.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": -1.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 37.0f, + "Rotation0": 25.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -40.0f, + "Rotation0": -40.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 1 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": -5.0f, + "Part": "RIGHT_ARM", + "Rotation1": 0.0f, + "Rotation0": -90.0f, + "Pivot0": 0.0f, + "Pivot1": 2.0f, + "Rotation2": 90.0f + }, + { + "Pivot2": 2.0f, + "Part": "LEFT_LEG", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "HEAD", + "Rotation1": -25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 6.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "BODY", + "Rotation1": -25.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -63.0f, + "Rotation0": -31.0f, + "Pivot0": -2.0f, + "Pivot1": 1.0f, + "Rotation2": -6.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 19, + "Smooth": 0b, + "ID": 15, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_HeavyHit_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json new file mode 100644 index 000000000..58a305e78 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Active.json @@ -0,0 +1,266 @@ +{ + "Loop": 3, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": 0.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -4.0f, + "Part": "HEAD", + "Rotation1": -37.0f, + "Rotation0": 56.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -202.0f, + "Rotation0": -75.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": -4.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 37.0f, + "Rotation0": -18.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 6.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -12.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 37.0f, + "Rotation0": -18.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 6.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -12.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 3 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.25f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 37.0f, + "Rotation0": -18.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 6.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_LEG", + "Rotation1": -12.0f, + "Rotation0": 18.0f, + "Pivot0": 1.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": 75.0f, + "Rotation0": -120.0f, + "Pivot0": -2.0f, + "Pivot1": -1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": 1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "RIGHT_LEG", + "Rotation1": 18.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 12.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 3, + "Smooth": 0b, + "ID": 22, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbDual_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json new file mode 100644 index 000000000..44c974b4c --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_OrbDual_Windup.json @@ -0,0 +1,327 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "FrameParts": [ + { + "Pivot2": 0.0f, + "Part": "RIGHT_ARM", + "Rotation1": -12.0f, + "Rotation0": -126.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": -63.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 18.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_LEG", + "Rotation1": -50.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 6.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": -12.0f, + "Pivot0": -1.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 6.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Duration": 15 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 88.0f, + "Rotation0": -151.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 12.0f, + "Rotation0": -31.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -18.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.75f, + "FrameParts": [ + { + "Pivot2": 6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 88.0f, + "Rotation0": -151.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 12.0f, + "Rotation0": -31.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -18.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": 6.0f, + "Part": "RIGHT_ARM", + "Rotation1": 88.0f, + "Rotation0": -151.0f, + "Pivot0": 2.0f, + "Pivot1": 0.0f, + "Rotation2": -18.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 12.0f, + "Rotation0": -31.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -132.0f, + "Rotation0": -25.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": -31.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 50.0f, + "Rotation0": -18.0f, + "Pivot0": 2.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 2.0f, + "Part": "RIGHT_LEG", + "Rotation1": 56.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 4 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -6.0f, + "Part": "RIGHT_ARM", + "Rotation1": -80.0f, + "Rotation0": 0.0f, + "Pivot0": 3.0f, + "Pivot1": 2.0f, + "Rotation2": -45.0f + }, + { + "Pivot2": -4.0f, + "Part": "HEAD", + "Rotation1": -37.0f, + "Rotation0": 56.0f, + "Pivot0": 2.0f, + "Pivot1": 3.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "LEFT_LEG", + "Rotation1": -25.0f, + "Rotation0": 25.0f, + "Pivot0": -1.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 0.0f, + "Part": "LEFT_ARM", + "Rotation1": -202.0f, + "Rotation0": -75.0f, + "Pivot0": 1.0f, + "Pivot1": 2.0f, + "Rotation2": 37.0f + }, + { + "Pivot2": -4.0f, + "Part": "BODY", + "Rotation1": -31.0f, + "Rotation0": 31.0f, + "Pivot0": 2.0f, + "Pivot1": 2.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 3 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 21, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_OrbDual_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json new file mode 100644 index 000000000..8ea8fc18b --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Active.json @@ -0,0 +1,77 @@ +{ + "Loop": 0, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 1.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": -63.0f + }, + { + "Pivot2": -9.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 69.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 7.0f, + "Rotation2": 63.0f + }, + { + "Pivot2": -4.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 56.0f, + "Pivot0": 0.0f, + "Pivot1": 4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -9.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 0, + "Smooth": 0b, + "ID": 20, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Shockwave_Active", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json new file mode 100644 index 000000000..2d45359b3 --- /dev/null +++ b/src/main/resources/assets/customnpcs/animations/Ability_Shockwave_Windup.json @@ -0,0 +1,203 @@ +{ + "Loop": -1, + "Speed": 1.0f, + "Frames": [ + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 2.0f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": -183.0f, + "Pivot0": -1.0f, + "Pivot1": -2.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": -183.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": -5.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 5 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 0.5f, + "FrameParts": [ + { + "Pivot2": 4.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": -183.0f, + "Pivot0": -1.0f, + "Pivot1": -2.0f, + "Rotation2": -12.0f + }, + { + "Pivot2": 3.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 4.0f, + "Part": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": -183.0f, + "Pivot0": 1.0f, + "Pivot1": -2.0f, + "Rotation2": 12.0f + }, + { + "Pivot2": -1.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 12.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -2.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": -25.0f, + "Pivot0": 0.0f, + "Pivot1": -5.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": 3.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": -18.0f, + "Pivot0": 0.0f, + "Pivot1": 1.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 18 + }, + { + "ColorMarker": 16777215, + "Comment": "", + "Speed": 3.0f, + "FrameParts": [ + { + "Pivot2": -7.0f, + "Part": "LEFT_ARM", + "Rotation1": -12.0f, + "Rotation0": 12.0f, + "Pivot0": -1.0f, + "Pivot1": 7.0f, + "Rotation2": -63.0f + }, + { + "Pivot2": -9.0f, + "Part": "HEAD", + "Rotation1": 0.0f, + "Rotation0": 69.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -7.0f, + "Part": "RIGHT_ARM", + "Rotation1": 12.0f, + "Rotation0": 12.0f, + "Pivot0": 1.0f, + "Pivot1": 7.0f, + "Rotation2": 63.0f + }, + { + "Pivot2": -4.0f, + "Part": "RIGHT_LEG", + "Rotation1": 0.0f, + "Rotation0": 56.0f, + "Pivot0": 0.0f, + "Pivot1": 4.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -6.0f, + "Part": "LEFT_LEG", + "Rotation1": 0.0f, + "Rotation0": 0.0f, + "Pivot0": 0.0f, + "Pivot1": 0.0f, + "Rotation2": 0.0f + }, + { + "Pivot2": -9.0f, + "Part": "BODY", + "Rotation1": 0.0f, + "Rotation0": 50.0f, + "Pivot0": 0.0f, + "Pivot1": 7.0f, + "Rotation2": 0.0f + } + ], + "Smooth": 0b, + "Duration": 2 + } + ], + "CurrentFrameTime": 0, + "CurrentFrame": 1, + "Smooth": 0b, + "ID": 19, + "WhileAttacking": 1b, + "WhileWalking": 1b, + "Name": "Ability_Shockwave_Windup", + "WhileStanding": 1b +} diff --git a/src/main/resources/assets/customnpcs/lang/en_US.lang b/src/main/resources/assets/customnpcs/lang/en_US.lang index fef02e070..3bc0fa119 100644 --- a/src/main/resources/assets/customnpcs/lang/en_US.lang +++ b/src/main/resources/assets/customnpcs/lang/en_US.lang @@ -164,6 +164,7 @@ gui.playerMap=Regen PlayerMap gui.unused=Unused gui.apply=Apply gui.cancel=Cancel +gui.continue=Continue gui.yes=Yes gui.lineColor1=Upper line color @@ -638,6 +639,7 @@ faction.friendly=Friendly faction.points=Points faction.ondeath=On death faction.hidden=Hidden +faction.hidden.hover=Hides this faction from the player's faction standings UI faction.default=Default faction.attackHostile=Attack hostile factions faction.defend=Defence faction members @@ -646,8 +648,9 @@ faction.options=Faction Options faction.increasepoints=Faction %s increased by %s points faction.decreasepoints=Faction %s decreased by %s points faction.attacked=Attacked by mobs +faction.attacked.hover=Whether vanilla mobs will target and attack NPCs in this faction faction.passive=Is Passive -faction.passive.hover=Passive factions will not queue any attacking tasks [Good for Performance] +faction.passive.hover=Passive faction NPCs cannot be damaged and will not queue any attacking tasks [Good for Performance] menu.inventory=Inventory menu.display=Display @@ -1537,6 +1540,48 @@ ability.target.aggro_target=Target ability.target.self=Self ability.target.aoe_self=AOE Self ability.target.aoe_target=AOE Target +ability.syncWindup=Sync Windup + +# Anchor Point +ability.anchor.front=Front +ability.anchor.center=Center +ability.anchor.rightHand=Right Hand +ability.anchor.leftHand=Left Hand +ability.anchor.aboveHead=Above Head +ability.anchor.chest=Chest + +# Sweep Mode +ability.sweep.swipe=Swipe +ability.sweep.spin=Spin + +# Dash Mode +ability.dash.aggressive=Aggressive +ability.dash.defensive=Defensive + +# Counter Type +ability.counter.flat=Flat +ability.counter.percent=Percent + +# Hazard Shape +ability.shape.circle=Circle +ability.shape.ring=Ring +ability.shape.cone=Cone + +# Placement Mode +ability.placement.atCaster=At Caster +ability.placement.atTarget=At Target +ability.placement.followCaster=Follow Caster +ability.placement.followTarget=Follow Target + +# Teleport Mode +ability.teleport.blink=Blink +ability.teleport.behind=Behind +ability.teleport.single=Single + +# Trap Placement +ability.trapPlace.atCaster=At Caster +ability.trapPlace.atTarget=At Target +ability.trapPlace.aheadOfCaster=Ahead of Caster telegraph.circle=Circle telegraph.ring=Ring @@ -1577,169 +1622,273 @@ ability.cnpc.disc=Disc ability.cnpc.laser_shot=Laser Shot ability.cnpc.sweeper=Sweeper -# Ability GUI - Type Tab +# ═══════════════════════════════════════════════════════════════ +# Ability Config GUI +# ═══════════════════════════════════════════════════════════════ + +# General Tab +ability.weight=Weight +ability.windUpTicks=Wind Up +ability.cooldownTicks=Cooldown +ability.lockMovement=Lock Movement +ability.rotationMode=Rotation +ability.rotationPhase=Phase +ability.rotation.free=Free +ability.rotation.locked=Locked +ability.rotation.track=Track +ability.interruptible=Interruptible +ability.dazedTicks=Dazed Ticks +ability.targetingMode=Targeting + +# Target Tab +ability.minRange=Min Range +ability.maxRange=Max Range +ability.conditions=Conditions + +# Effects Tab +ability.windUpSound=Wind Up Sound +ability.activeSound=Active Sound +ability.counterSound=Counter Sound +ability.windUpAnimation=Wind Up Animation +ability.activeAnimation=Active Animation +ability.counterAnimation=Counter Animation +ability.showTelegraph=Show Telegraph +ability.windUpColor=Wind Up Color +ability.activeColor=Active Color + +# Section Headers +ability.section.timing=Timing +ability.section.movement=Movement +ability.section.sounds=Sounds +ability.section.animations=Animations +ability.section.telegraph=Telegraph +ability.section.beam=Beam +ability.section.sweep=Sweep +ability.section.push=Push +ability.section.leap=Leap +ability.section.disc=Disc +ability.section.homing=Homing +ability.section.boomerang=Boomerang +ability.section.explosive=Explosive +ability.section.colors=Colors +ability.section.effects=Effects +ability.section.burst=Burst +ability.section.visual=Visual +ability.section.projectile1=Projectile 1 +ability.section.projectile2=Projectile 2 +ability.section.projectile3=Projectile 3 +ability.section.projectile4=Projectile 4 +ability.section.projectile5=Projectile 5 +ability.section.projectile6=Projectile 6 +ability.section.projectile7=Projectile 7 +ability.section.projectile8=Projectile 8 +ability.section.counter=Counter +ability.section.area=Area +ability.section.damage=Damage +ability.section.debuffs=Debuffs +ability.section.healing=Healing +ability.section.trigger=Trigger +ability.section.aoe=AOE +ability.section.pullDamage=Pull Damage +ability.section.hitZone=Hit Zone + +# Shared Sub-Section Labels (used under section headers) +gui.radius=Radius +gui.thickness=Thickness +gui.rotationSpeed=Rotation Speed +gui.strength=Strength +gui.range=Range +gui.delay=Delay +gui.density=Density +gui.length=Length +gui.width=Width +gui.height=Height +gui.value=Value +gui.chance=Chance +gui.sound=Sound +gui.animation=Animation +gui.duration=Duration +gui.amp=Amp +gui.speed=Speed # Common Type Settings ability.radius=Radius ability.knockback=Knockback -ability.knockbackUp=KB Up -ability.maxDist=Max Dist -ability.minDist=Min Dist +ability.knockbackUp=Knockback Up ability.distance=Distance +ability.maxDistance=Max Distance ability.lifetime=Lifetime -ability.stunTicks=Stun -ability.leapHeight=Leap Height +ability.stunTicks=Stun Ticks ability.hitWidth=Hit Width +ability.hitLength=Hit Length ability.effects=Effects -gui.duration=Duration -gui.amp=Amp +ability.mode=Mode +ability.duration=Duration +ability.anchorPoint=Anchor Point +ability.anchor.offsetX=Offset X +ability.anchor.offsetY=Offset Y +ability.anchor.offsetZ=Offset Z +ability.vertical=Vertical +ability.rotationSpeed=Rotation Speed -# Slam Settings +# Slam ability.leapSpeed=Leap Speed +ability.leapHeight=Leap Height -# Charge Settings -ability.hitRadius=Hit Radius - -# Cutter Settings +# Cutter +ability.range=Range +ability.sweepMode=Sweep Mode +ability.spinDuration=Spin Duration ability.arcAngle=Arc Angle -ability.sweepWaves=Waves -ability.rotSpeed=Rot Speed -ability.piercing=Piercing +ability.innerRadius=Inner Radius + +# Projectile +ability.projectileType=Projectile Type # Orb Settings ability.homing=Homing ability.explosive=Explosive +ability.firingSpeed=Firing Speed +ability.amount=Amount +ability.dualCharge=Dual Charging -# Vortex Settings -ability.pullRadius=Radius -ability.pullStrength=Strength -ability.pullTo=Pull To -ability.aoe=AOE +# Charge +ability.chargeSpeed=Charge Speed + +# Dash +ability.dashMode=Dash Mode +ability.dashDistance=Dash Distance +ability.dashSpeed=Dash Speed + +# Teleport +ability.blinkRadius=Blink Radius +ability.blinkCount=Blink Count +ability.blinkDelay=Blink Delay +ability.behindDistance=Behind Distance +ability.lineOfSight=Line of Sight +ability.damageAtStart=Damage At Start +ability.damageAtEnd=Damage At End + +# Vortex +ability.pullRadius=Pull Radius +ability.pullStrength=Pull Strength ability.maxTargets=Max Targets -# Dash Settings -ability.dash.aggressive=Aggressive -ability.dash.defensive=Defensive -ability.mode=Mode -ability.behindDistance=Behind Dist +# Shockwave +ability.pushStrength=Push Strength -# Teleport Settings -ability.blinkCount=Blinks -ability.blinkDelay=Delay -ability.blinkRadius=Radius -ability.minRadius=Min Rad -ability.dmgRadius=Dmg Radius -ability.lineOfSight=Line Sight -ability.dmgAtStart=Dmg Start +# Guard +ability.damageReduction=Damage Reduction +ability.counterWindow=Counter Ticks -# Projectile Settings -ability.explRadius=Expl Rad - -# Beam Settings -ability.beamLength=Length -ability.beamWidth=Width -ability.beamHeight=Height -ability.dmgInterval=Interval -ability.sweepAngle=Sweep Ang -ability.sweepSpeed=Sweep Spd -ability.lockTarget=Lock Tgt -ability.rotations=Rotations - -# Guard Settings -ability.dmgReduce=Dmg Reduce -ability.counterDmg=Counter Dmg -ability.canCounter=Counter -ability.counterChance=Counter % -ability.counterType=Counter Type -ability.counterValue=Counter Value -ability.counterSound=Counter Sound -ability.counterAnim=Counter Anim - -# Heal Settings -ability.healAmount=Amount -ability.healPercent=Percent -ability.healRadius=Radius +# Heal +ability.instantHeal=Instant Heal +ability.healAmount=Heal Amount +ability.healPercent=Heal Percent +ability.healRadius=Heal Radius ability.healSelf=Heal Self ability.healAllies=Heal Allies -# Hazard Settings -ability.dmgPerSec=Dmg/Sec -ability.debuffDur=Debuff Dur +# Hazard ability.shape=Shape ability.placement=Placement -ability.affectsCaster=Hit Caster -ability.ignoreInvuln=Ign Invuln -ability.place.caster=At Caster -ability.place.target=At Target -ability.place.followCaster=Follow Caster -ability.place.followTarget=Follow Target -ability.place.ahead=Ahead +ability.damagePerSecond=Damage/Sec +ability.damageInterval=Damage Interval +ability.slownessLevel=Slowness Level +ability.debuffDuration=Debuff Duration +ability.poisonLevel=Poison Level +ability.affectsCaster=Affects Caster -# Trap Settings -ability.triggerRadius=Trig Rad +# Trap ability.armTime=Arm Time -ability.maxTriggers=Max Trig +ability.maxTriggers=Max Triggers +ability.triggerCooldown=Trigger Cooldown -# Disc Settings -ability.discRadius=Disc Rad -ability.discThickness=Thickness -ability.boomerang=Boomerang -ability.boomerangDelay=Return Delay -ability.homingStr=Homing Str -ability.homingRange=Homing Rng -ability.explosionRad=Expl Rad -ability.rotationSpeed=Rot Speed +# Sweeper +ability.sweepSpeed=Sweep Speed +ability.rotations=Rotations +ability.piercing=Piercing +ability.lockTarget=Lock Target + +# Beam / Laser +ability.beamWidth=Beam Width +ability.headSize=Head Size +ability.attachedToOwner=Attached to Owner +ability.laserWidth=Laser Width +ability.expansionSpeed=Expansion Speed +ability.lingerTicks=Linger Ticks + +# Visual Settings ability.innerColor=Inner Color ability.outerColor=Outer Color ability.outerEnabled=Outer Glow ability.outerWidth=Outer Width +ability.outerAlpha=Outer Alpha ability.lightning=Lightning ability.lightningDensity=Density ability.lightningRadius=Radius -ability.anchorPoint=Anchor Point -ability.noVisualSettings=No visual settings for this ability type -# Laser Shot Settings -ability.laserWidth=Laser Width -ability.expansionSpeed=Expansion Spd -ability.lingerTicks=Linger Ticks +# Projectile Count / Settings +ability.projectileCount=Count +ability.dualFireDelay=Fire Delay +ability.fireDelay=Fire Delay +ability.colorOverride=Color Override -# Energy Beam Settings -ability.headSize=Head Size -ability.attachedToOwner=Attached +# Burst System +ability.burstEnabled=Burst +ability.burstAmount=Amount +ability.burstDelay=Delay +ability.burstReplayAnimations=Replay Animations +ability.burstOverlap=Overlap +ability.hover.burstOverlap=When enabled, projectiles from previous bursts keep flying while new ones fire +ability.hover.burstReplay=Replay windup and active animations for each burst iteration # Ability Save/Load ability.save.confirm=Save ability preset ability.save.overwrite=Overwrite existing preset +ability.duplicate.name=A preset with this name already exists ability.load.select=Select ability to load: +ability.load.mode=How should this ability be loaded? +ability.clone=Clone +ability.reference=Reference ability.delete.confirm=Delete ability preset gui.load=Load +# Ability Edit Mode +ability.edit.mode=How should this ability be edited? +ability.cloneModify=Clone & Edit +ability.modifyParent=Edit Parent + +# Ability Variant Selection +ability.selectVariant=Select Variant +ability.variant.single=Single +ability.variant.dual=Dual +ability.variant.barrage=Barrage + +# Ability Type Selection +ability.selectType=Select Ability Type: + # Global Abilities Manager ability.manager.title=Ability Manager # Explosive Hover Text ability.explosive.noBlockDamage=Explosions do not destroy blocks -# Additional Orb Settings -ability.explRadius=Expl Radius - -# Telegraph Colors (for abilities that support separate colors) -ability.windUpColor=Wind Up Color -ability.activeColor=Active Color - -# Shockwave Settings -ability.pushRadius=Push Radius -ability.pushStrength=Push Str +# Shockwave Settings (dev) ability.shockwaveFalloff=Damage/knockback drop off with distance -# Ability Config GUI +# Ability Config GUI (dev) ability.typeId=Type ID -ability.conditions=Conditions ability.noTypeSettings=No type-specific settings +# ═══════════════════════════════════════════════════════════════ +# Ability Hover Tooltips +# ═══════════════════════════════════════════════════════════════ + ability.hover.weight=Higher weight = more likely to be chosen when multiple abilities available -ability.hover.lockMove=Prevents NPC from moving while ability is charging or active +ability.hover.lockMovement=Prevents NPC pathfinding during the selected phases (Windup, Active, or Both) +ability.hover.rotationMode=Free: normal AI rotation. Locked: freeze facing direction. Track: force face target for precise aiming. +ability.hover.rotationPhase=When the rotation mode applies (Windup, Active, or Both) ability.hover.interruptible=If enabled, ability can be interrupted by taking damage ability.hover.dazed=Stun duration in ticks if ability is interrupted (20 ticks = 1 second) ability.hover.windup=Charge-up time before ability activates (20 ticks = 1 second) @@ -1760,6 +1909,8 @@ ability.hover.piercing=Hits multiple targets instead of stopping on first hit ability.hover.lightning=Add electrical effect to visuals ability.hover.outerGlow=Enable outer glow layer around projectile ability.hover.anchorPoint=Where on the NPC the ability spawns from +ability.hover.vertical=Disc flies standing up with thin edge facing target (like a saw blade) +ability.hover.dualCharge=Whether or not should create two anchor points ability.hover.damage=Base damage dealt to targets ability.hover.speed=Movement speed of projectile ability.hover.lifetime=Maximum ticks before despawning diff --git a/src/main/resources/assets/customnpcs/textures/gui/cloner/folder.png b/src/main/resources/assets/customnpcs/textures/gui/cloner/folder.png new file mode 100644 index 000000000..d98408b92 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/cloner/folder.png differ diff --git a/src/main/resources/assets/customnpcs/textures/gui/cloner/tab.png b/src/main/resources/assets/customnpcs/textures/gui/cloner/tab.png new file mode 100644 index 000000000..a041d03b0 Binary files /dev/null and b/src/main/resources/assets/customnpcs/textures/gui/cloner/tab.png differ diff --git a/tools/bukkit-api/Vault-1.4.1.jar b/tools/bukkit-api/Vault-1.4.1.jar new file mode 100644 index 000000000..d4d4ecc76 Binary files /dev/null and b/tools/bukkit-api/Vault-1.4.1.jar differ diff --git a/tools/bukkit-api/spigot-api-ONLY.jar b/tools/bukkit-api/spigot-api-ONLY.jar new file mode 100644 index 000000000..a8028aeab Binary files /dev/null and b/tools/bukkit-api/spigot-api-ONLY.jar differ