Merge Dev to Main [deploy-docs]
No files matched your search
@@ -1,92 +0,0 @@
|
||||
# CNPC+ 1.11 Beta - The Scripting Update
|
||||
|
||||
🟡 **In Testing**
|
||||
|
||||
|
||||
|
||||
## Features: ⚒️
|
||||
|
||||
- **Syntax Highlighting:**
|
||||
|
||||
> Full color-coded script editor. Keywords, types, variables, methods, strings, and comments are all distinct. Scope-aware coloring distinguishes local fields from globals and chained method calls.
|
||||
|
||||
|
||||
|
||||
- **Autocomplete:**
|
||||
|
||||
> Smart suggestions as you type. Context-aware for static vs instance access, shows method parameters, resolves chained calls, and suggests auto imports for classes. Frequently used members prioritized.
|
||||
|
||||
|
||||
|
||||
- **Error Detection:**
|
||||
|
||||
> Catch mistakes before running. Type mismatches, wrong arguments, missing methods, unused imports, duplicate definitions, and more -- all underlined with hover messages explaining the issue.
|
||||
|
||||
|
||||
|
||||
- **Hover Information:**
|
||||
|
||||
> Hover any symbol to see its type, documentation, and declaration. Works on methods, fields, classes, and even generics. Click to pin tooltips in place.
|
||||
|
||||
|
||||
|
||||
- **Script Editor Overhaul:**
|
||||
|
||||
> - **Line Numbers** - Gutter with current line highlighting.
|
||||
> - **Go To Line** - CTRL+G to jump to any line.
|
||||
> - **Search & Replace** - CTRL+F / CTRL+H with real-time highlighting.
|
||||
> - **Go To Definition** - CTRL+Click to jump to any symbol.
|
||||
> - **Smart Undo/Redo** - Word-level instead of character-level.
|
||||
> - **Line Operations** - Duplicate, delete, move up/down.
|
||||
> - **Comment Toggle** - CTRL+/ for selected lines.
|
||||
> - **Rename** - Rename a symbol across all occurrences.
|
||||
> - **Smooth Scrolling** - Eased scroll animation.
|
||||
> - **Indent Guides** - Scope-highlighted vertical indent lines.
|
||||
> - **Brace Matching** - Highlighted pairs, red for unclosed.
|
||||
> - **Smart Brackets** - Auto-pairing for `{}`, `()`, `[]`, `""`, `''`.
|
||||
> - **Fullscreen Mode** - Expand editor to fill the game window.
|
||||
> - **Shortcut Overlay** - View all keyboard shortcuts at a glance.
|
||||
|
||||
|
||||
|
||||
- **Java Scripting (Janino):**
|
||||
|
||||
> Write scripts in real Java compiled at runtime. Name methods after hooks for automatic wiring. Language selector per tab to switch between Java and JavaScript. External `.java` file support.
|
||||
|
||||
|
||||
|
||||
- **Client-Side Scripting:**
|
||||
|
||||
> Run scripts on the client for responsive experiences. Server-controlled -- off by default, must be explicitly enabled. Script files sync automatically on login and reload.
|
||||
|
||||
|
||||
|
||||
- **Cloner Tab Overhaul:**
|
||||
|
||||
> Folder-based organization for saved NPCs, items, and entries. Full-width directory browser for large collections. Improved tab navigation.
|
||||
|
||||
|
||||
|
||||
- **Addon API Support:**
|
||||
|
||||
> Addons can ship type definitions that load into the script editor automatically. Full autocomplete, hover info, and documentation for addon APIs. Addons can extend existing CNPC+ types with new methods.
|
||||
|
||||
|
||||
|
||||
- **Animation Improvements:**
|
||||
|
||||
> Data store for passing data across animation events and frames. New consumer-based task system for animation lifecycle. Expanded scripting API for animation control.
|
||||
|
||||
|
||||
|
||||
**Extras**
|
||||
|
||||
- Player Dialog Events now work like NPC Dialog Events.
|
||||
- Attack speed configuration for linked items.
|
||||
- Client-side balance prediction during Trader interactions.
|
||||
- Right-click cycling on multi-option NPC buttons (Hair, Eyes, Fur, etc.).
|
||||
- Fixed quest cooldown for MC Custom and RL Custom timer types.
|
||||
- Fixed Bard music restarting when opening dialogs.
|
||||
- Fixed NPC biome spawn settings not saving after editing.
|
||||
- Fixed block waypoint issues.
|
||||
- Fixed script config syncing between server and client.
|
||||
@@ -1,118 +0,0 @@
|
||||
# ✏️ CustomNPC+ 1.11 - The Scripting Update ✏️
|
||||
|
||||
---
|
||||
|
||||
The **Scripting Update** completely transforms how you write scripts in CNPC+! A brand new **Script Editor** with **syntax highlighting**, **autocomplete**, and **error detection** makes scripting feel like a real IDE. Write scripts in **Java** with the new Janino engine, enable **client-side scripting** for responsive experiences, and organize your Cloner with **folders**!
|
||||
|
||||
---
|
||||
|
||||
## Script Editor 📝
|
||||
|
||||
The script editor has been rebuilt from the ground up into a **full-featured code editor** right inside Minecraft.
|
||||
|
||||
### Writing Code
|
||||
|
||||
- **Syntax Highlighting** - Keywords, types, variables, methods, strings, and comments are all color-coded automatically. The editor understands your code -- local variables, global fields, and chained method calls each get their own color
|
||||
- **Autocomplete** - Start typing and get smart suggestions for methods, fields, and classes. Suggestions know whether you're in a static or instance context, and frequently used members appear first
|
||||
- **Auto Imports** - Type a class name and the editor suggests the correct import for you
|
||||
- **Error Detection** - Catch mistakes before you even run your script! Wrong argument types, missing methods, type mismatches, unused imports, and more are all underlined with detailed error messages on hover
|
||||
|
||||
> Hover over any symbol to see its **full type information**, documentation, and declaration -- just like a desktop IDE.
|
||||
|
||||
---
|
||||
|
||||
### Navigation
|
||||
|
||||
- **Go To Line** - `CTRL+G` jumps to any line instantly
|
||||
- **Search & Replace** - `CTRL+F` to search, `CTRL+H` to replace. All matches highlight in real-time
|
||||
- **Go To Definition** - `CTRL+Click` any method, field, or type to jump straight to its definition
|
||||
- **Fullscreen Mode** - Expand the editor to fill your entire game window for maximum workspace
|
||||
|
||||
### Editing
|
||||
|
||||
- **Undo/Redo** - Smart undo that works on whole words at a time, not individual characters
|
||||
- **Line Operations** - Duplicate lines with `CTRL+D`, delete lines, and move lines up or down with shortcuts
|
||||
- **Comment Toggle** - `CTRL+/` to comment or uncomment selected lines
|
||||
- **Rename** - Rename a variable or method and every occurrence updates at once
|
||||
- **Copy Whole Line** - Copy with nothing selected grabs the entire line
|
||||
- **Triple Click** - Select an entire line instantly
|
||||
|
||||
### Visual Polish
|
||||
|
||||
- **Line Numbers** - A clean gutter with line numbers and current line highlighting
|
||||
- **Smooth Scrolling** - Eased scroll animations for a polished feel
|
||||
- **Indent Guides** - Vertical lines show your code's nesting depth, with the current scope highlighted in green
|
||||
- **Brace Matching** - Matching `{}` braces light up, and unclosed braces turn red
|
||||
- **Smart Brackets** - Typing `{` automatically creates the closing `}` with correct indentation. Same for `()`, `[]`, `""`, and `''`
|
||||
- **Keyboard Shortcut Overlay** - Press a button to see all available shortcuts at a glance
|
||||
|
||||
---
|
||||
|
||||
## Java Scripting ☕
|
||||
|
||||
Write scripts in **real Java** instead of JavaScript! Powered by the **Janino** compiler, your Java code is compiled and runs natively.
|
||||
|
||||
- **Full Java Language** - Use classes, interfaces, enums, generics, lambdas, and everything you know from Java
|
||||
- **Automatic Hook Resolution** - Just name your methods after the hook you want (e.g., `init`, `tick`, `interact`) and they're wired up automatically
|
||||
- **Language Selector** - Each script tab has a dropdown to choose between JavaScript and Java. Mix and match across tabs
|
||||
- **External Files** - Write `.java` scripts in an external editor and they're loaded automatically
|
||||
|
||||
> Java and JavaScript scripts coexist side by side. Pick whichever language fits your workflow!
|
||||
|
||||
---
|
||||
|
||||
## Client-Side Scripting 🖥️
|
||||
|
||||
Scripts can now run **on the client** for responsive, visual experiences!
|
||||
|
||||
- **Server Controlled** - Server owners decide whether client scripting is allowed. Players can't enable it on their own
|
||||
- **Automatic Sync** - Script files are sent from the server to all connected clients on login, and re-synced whenever scripts are reloaded
|
||||
- **Safe by Default** - Client scripting is off by default and must be explicitly enabled in the server config
|
||||
|
||||
> Client-side scripts open the door to custom UI effects, visual feedback, and client-only hooks -- all while the server stays in full control.
|
||||
|
||||
---
|
||||
|
||||
## Cloner Tab Overhaul 📂
|
||||
|
||||
The Cloner now supports **folders** for organizing your saved NPCs, items, and entries!
|
||||
|
||||
- **Folder System** - Create folders and subfolders to keep your cloner organized however you like
|
||||
- **Full Screen Browser** - A new full-width directory view makes browsing large collections much easier
|
||||
- **Improved Tabs** - Better tab navigation for switching between cloner categories
|
||||
|
||||
---
|
||||
|
||||
## Addon API Support 📘
|
||||
|
||||
Addon developers can now ship **type definitions** alongside their mods, giving scripters full autocomplete and documentation for addon APIs!
|
||||
|
||||
- **Automatic Loading** - Any mod can include API definitions and they'll appear in the script editor automatically
|
||||
- **Patch Support** - Addons can extend existing CNPC+ types with new methods (e.g., a DBC addon adding `getDBCPlayer()` to the Player type)
|
||||
- **Full Documentation** - Parameter names, return types, and descriptions all show up in autocomplete and hover info
|
||||
|
||||
> If you're a scripter using addons, you get autocomplete for their APIs with zero setup. If you're an addon developer, just include your definitions and everything works.
|
||||
|
||||
---
|
||||
|
||||
## Animation Improvements 🎬
|
||||
|
||||
- **Data Store** - Animations can now store and pass data across events and frames for more complex animation logic
|
||||
- **Task System** - A new consumer-based system for reacting to animation lifecycle events, replacing the old approach
|
||||
- **Expanded API** - More animation control exposed to the scripting API
|
||||
|
||||
---
|
||||
|
||||
## Additional Changes 🔧
|
||||
|
||||
- **Player Dialog Events** - Now work the same way as NPC Dialog Events for consistency
|
||||
- **Linked Item Attack Speed** - Added attack speed configuration to linked items
|
||||
- **Trader Balance Preview** - Client-side balance prediction shows your expected balance during trades
|
||||
- **Right-Click Cycling** - Multi-option NPC buttons (Hair, Eyes, Fur, etc.) can now be right-clicked to cycle backwards
|
||||
- **Quest Cooldown Fix** - Fixed cooldown not working for MC Custom and RL Custom timer types
|
||||
- **Bard Music Fix** - Fixed music restarting or duplicating when opening dialogs
|
||||
- **Biome Spawn Fix** - Fixed NPC biome spawn settings not saving after editing
|
||||
- **Block Waypoint Fix** - Fixed issues with block waypoints
|
||||
- **Script Config Fix** - Fixed script configuration not syncing properly between server and client
|
||||
|
||||
---
|
||||
@@ -1,368 +0,0 @@
|
||||
# ⚔️ 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, set **traps** and **hazards**, chain abilities into devastating combos, 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. Supports both a **universal cooldown** and **per-ability cooldowns**
|
||||
- **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
|
||||
- **Invulnerability** - Make the caster invulnerable during Wind-up, Active, or both phases
|
||||
- **Ignore I-Frames** - Bypass Minecraft's damage immunity timer, allowing rapid consecutive hits
|
||||
- **Free on Cast** - The ability enters cooldown the moment it launches, freeing the caster while spawned entities (projectiles, zones, barriers) persist independently
|
||||
- **Magic Damage** - Abilities can deal magic damage as a separate damage type, with configurable damage values and split ratios
|
||||
|
||||
> 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. Air slams deal reduced damage based on required leap height
|
||||
- **Heavy Hit** - A single powerful melee strike with bonus knockback and a configurable hit delay
|
||||
- **Cutter** - A slashing arc attack in a cone. Configurable angle and reach
|
||||
|
||||
> 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. Energy projectiles use a **Variant System** — each base type (Orb, Beam, Disc) can be configured with variants like dual-fire or barrage patterns, all from within the same ability type.
|
||||
|
||||
### Orbs
|
||||
|
||||
Homing energy spheres that track their target through the air. Configurable with variants for dual or barrage firing patterns.
|
||||
|
||||
### Discs
|
||||
|
||||
Flat spinning projectiles with optional **boomerang** behavior. Supports both vertical and horizontal orientation.
|
||||
|
||||
### Beams
|
||||
|
||||
Sustained energy beams that connect the caster to their target. Supports a **Free Aim** mode for manual aiming without homing.
|
||||
|
||||
### Laser Shot
|
||||
|
||||
An **instant-fire** hitscan projectile with configurable width and speed. No homing — pure aim.
|
||||
|
||||
### 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. Supports custom offset anchors and a **Launch From Anchor** setting
|
||||
- **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
|
||||
- **Hit Type** - Choose how the projectile interacts with targets: **Single** (hits one), **Pierce** (passes through), or **Multi** (hits multiple)
|
||||
- **Lifespan** - Projectile speed, max age, and max travel distance (up to 150 blocks)
|
||||
- **Explosions** - Energy projectiles can detonate on impact with configurable explosion radius. Block damage can be toggled in the Energy Config
|
||||
|
||||
---
|
||||
|
||||
## Energy Barriers 🛡️
|
||||
|
||||
Defensive energy constructs that block incoming projectiles and attacks.
|
||||
|
||||
- **Dome** - A spherical barrier centered on the caster. Blocks incoming energy projectiles with configurable per-type damage multipliers, HP/durability, and duration
|
||||
- **Wall** - A placeable flat energy panel with configurable dimensions and height offset. Has an optional **launch mode** that fires the wall forward, dealing damage and knockback
|
||||
- **Shield** - A held energy panel that follows the caster's facing direction for directional blocking
|
||||
|
||||
**Barrier Properties:**
|
||||
- **HP & Durability** - Barriers have health and break when depleted
|
||||
- **Melee Vulnerability** - Barriers can be configured to take damage from melee attacks
|
||||
- **Damage Absorption** - Attacks aimed at the caster can be redirected to damage the barrier instead
|
||||
- **Ally/Target Filtering** - Configure which projectiles are blocked based on ownership
|
||||
- **Offset Support** - Position barriers with custom offsets from the caster
|
||||
|
||||
---
|
||||
|
||||
## Defensive Abilities 🏰
|
||||
|
||||
Reactive defensive stances that protect the caster when hit.
|
||||
|
||||
- **Guard** - Enter a defensive stance that **reduces incoming damage** by a configurable percentage. Lasts until duration expires or a max hit count is reached
|
||||
- **Counter** - Absorb incoming attacks and **counter-attack the attacker**. Counter damage can be a flat value or a percentage of the absorbed damage. Plays a counter-attack animation on each successful counter
|
||||
- **Dodge** - Fully **evade incoming attacks**, negating all damage. Plays randomized dodge animations from up to three configurable animation slots
|
||||
|
||||
> All defensive abilities support configurable duration and maximum hit counts before they break.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
- **Shockwave** - An AOE burst radiating outward from the caster, dealing damage and knockback in a configurable radius
|
||||
- **Sweeper** - A wide rotational sweep attack around the caster with configurable radius and rotation speed. Can run concurrently with other abilities in chains
|
||||
- **Vortex** - Creates a pulling force that drags nearby entities toward the center while dealing damage
|
||||
|
||||
---
|
||||
|
||||
## Hazards & Traps 🪤
|
||||
|
||||
Ground-based zone abilities for area denial and ambush tactics.
|
||||
|
||||
### Hazards
|
||||
|
||||
Persistent damaging areas that continuously hurt entities standing inside them. Configurable damage interval, zone count (up to 20), shape (circle or square), zone height, and duration. Can optionally affect the caster.
|
||||
|
||||
**Zone Visual Presets:** Default, Toxic, Inferno, Arcane, Electric, Frost — each with themed colors, particles, and visual effects.
|
||||
|
||||
### Traps
|
||||
|
||||
Proximity-triggered burst abilities that sit dormant until an entity enters the trigger radius. Support configurable arm time, multiple triggers before expiring, trigger cooldown, damage radius, and knockback. Traps can be **hidden** (invisible) until triggered, revealing with a brief burst effect.
|
||||
|
||||
**Trap Presets:**
|
||||
- **Hidden** - Minimal visibility, no effects — a pure stealth trap
|
||||
- **Venom** - Applies Poison with toxic green visuals
|
||||
- **Explosive** - Applies Fire with fiery orange particles
|
||||
- **Cursed** - Applies Weakness with purple arcane effects
|
||||
- **Shock** - Applies Mining Fatigue with blue electrical sparks
|
||||
- **Snare** - Applies Slowness with icy blue visuals
|
||||
|
||||
### Zone Visuals
|
||||
|
||||
Both hazards and traps share a rich visual system with configurable layers: ground fill, concentric rings, rotating borders, accents (static, swaying, or flickering), lightning arcs, and particle effects with multiple motion types (rising, drifting, sparks).
|
||||
|
||||
---
|
||||
|
||||
## Ability Effect 💫
|
||||
|
||||
A support ability for applying buffs, debuffs, healing, and custom effects to allies or enemies.
|
||||
|
||||
**Targeting:**
|
||||
- **Self** - Affect only the caster (self-buffs, self-healing)
|
||||
- **AOE Self** - Area-of-effect centered on the caster with a configurable radius
|
||||
|
||||
**Target Filter (AOE):**
|
||||
- **Allies** - Only affect friendly entities
|
||||
- **Enemies** - Only affect hostile entities
|
||||
- **All** - Affect everyone in range
|
||||
|
||||
Allies are determined by **Party** for players and **Faction** for NPCs. A toggle controls whether the caster is included in AOE effects.
|
||||
|
||||
**Effect Types:**
|
||||
- Flat and percentage-based healing (instant or over time)
|
||||
- Vanilla potion effects
|
||||
- Custom effects from the Custom Effect system
|
||||
- Mod-registered effect actions
|
||||
|
||||
**Built-in Variants:** Self Heal, Healing Aura, Poison Debuff.
|
||||
|
||||
---
|
||||
|
||||
## Custom Ability 🔧
|
||||
|
||||
A blank-slate ability type designed for **scripters** to build fully custom abilities through script hooks.
|
||||
|
||||
**Script Hooks:**
|
||||
- **Start** - Fired when the ability begins
|
||||
- **Execute** - Fired when entering the active phase
|
||||
- **Tick** - Fired every game tick with phase and tick count
|
||||
- **Complete** - Fired when the ability finishes
|
||||
- **Toggle / Toggle Tick** - For toggle-mode abilities with multiple states
|
||||
|
||||
**Features:**
|
||||
- Full telegraph control with all shape types (Circle, Ring, Line, Cone, Point, Square)
|
||||
- Configurable telegraph dimensions, colors, and duration
|
||||
- Supports both instant execution and multi-state toggle modes
|
||||
|
||||
---
|
||||
|
||||
## Burst System 🔁
|
||||
|
||||
Abilities can be configured to **fire multiple times in rapid succession** as a single use.
|
||||
|
||||
- **Burst Amount** - Number of additional repetitions after the initial cast
|
||||
- **Burst Delay** - Ticks between each burst iteration
|
||||
- **Replay Animations** - Optionally replay the wind-up animation on each burst
|
||||
- **Overlap Mode** - Previous entities can persist while the next burst fires, allowing stacking effects
|
||||
|
||||
> Burst is available on most ability types including energy projectiles, melee abilities, and movement abilities.
|
||||
|
||||
---
|
||||
|
||||
## Chained Abilities ⛓️
|
||||
|
||||
Chain multiple abilities together into **sequential combos** that execute one after another.
|
||||
|
||||
- **Ordered Entries** - Each entry in the chain references an ability with a configurable delay before it fires
|
||||
- **Wind-up All** - Optionally wind up all abilities simultaneously before the chain begins
|
||||
- **Chain Cooldown** - A single cooldown applied after the entire chain completes
|
||||
- **Chain Conditions** - Conditions checked once for the whole chain, not per-ability
|
||||
|
||||
### Concurrency
|
||||
|
||||
Specific ability types can be marked to run **concurrently** within a chain — executing alongside the primary ability instead of waiting in sequence. Concurrent-capable types include Effect, Hazard, Trap, and Sweeper.
|
||||
|
||||
> Chained abilities work with the ability hotbar and support live previewing in the editor.
|
||||
|
||||
---
|
||||
|
||||
## Telegraph System 📍
|
||||
|
||||
**Telegraphs** are visual ground indicators that warn players before an ability lands. They appear during the wind-up phase and transition into a warning state before 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
|
||||
- **Square** - Square area 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
|
||||
- **Height Handling** - Telegraphs properly handle ground and air positioning
|
||||
- **Custom Controls** - Full telegraph configuration available on Custom Abilities
|
||||
|
||||
> 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
|
||||
- **Dazed Animation** - Plays during the dazed recovery state
|
||||
- **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
|
||||
- **Multiple Animations** - Multiple animations can be registered under one common name
|
||||
|
||||
> 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. Supports both preset effect types and **manual potion IDs** for custom or modded effects with amplification up to 255.
|
||||
|
||||
**Available Preset Effects:**
|
||||
Fire, Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue
|
||||
|
||||
### Conditions
|
||||
|
||||
Abilities support a **condition system** that controls when they can be used. Each condition can be checked on the **Caster**, the **Target**, or **Both**.
|
||||
|
||||
**Condition Types:**
|
||||
- **HP Threshold** - Check if an entity's health is above, below, or equal to a value (supports flat or percentage)
|
||||
- **Hit Count** - Require the caster to have been hit a certain number of times within a time window
|
||||
- **Has Item** - Check if an entity is holding, wearing, or carrying a specific item
|
||||
- **Quest Completed** - Check if a player has completed a specific quest
|
||||
- **Has Effect** - Check if an entity has a specific custom effect applied
|
||||
|
||||
---
|
||||
|
||||
## Player Abilities 🧑
|
||||
|
||||
Players can unlock and use abilities with a full hotbar and management system!
|
||||
|
||||
### Ability Hotbar
|
||||
|
||||
The **Ability Hotbar** is a 12-slot bar for equipping and switching between unlocked abilities. Hold the **HUD Key** and use the **scroll wheel** to cycle through your equipped abilities. The hotbar displays ability icons with cooldown progress and supports horizontal or vertical layouts with 3, 5, or 7 visible slots.
|
||||
|
||||
Configure your hotbar through drag-and-drop in the **CNPC+ Inventory Ability Tab**, and customize its appearance in the **HUD Editor** under CNPC+ Inventory Settings.
|
||||
|
||||
### Player Features
|
||||
- **Unlock System** - Players receive abilities via scripting or commands
|
||||
- **Per-Ability Cooldowns** - Each ability can have its own cooldown in addition to the universal cooldown
|
||||
- **Cancel on Double-Tap** - Double-tap the ability key during wind-up to cancel and immediately enter cooldown
|
||||
- **Ability Visibility** - Hide or show specific abilities in the HUD and usage
|
||||
- **State Management** - Abilities are properly cancelled on logout, dimension change, death, and respawn. Movement input is suppressed during ability locks
|
||||
- **Flight Safety** - Abilities do not affect players who are flying
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
- **PlayerAbilityEvent** - Events for player ability actions
|
||||
|
||||
### Energy Projectile Scripting
|
||||
|
||||
Full scripting interfaces for all energy projectile types with 5 event hooks:
|
||||
- **Fired** - When the projectile launches
|
||||
- **Update** - Every tick during flight
|
||||
- **EntityImpact** - On hitting an entity
|
||||
- **BlockImpact** - On hitting a block
|
||||
- **Expired** - When the projectile's lifespan ends
|
||||
|
||||
### Ability Extender System
|
||||
|
||||
Register custom **lifecycle hooks** on abilities with the Ability Extender system:
|
||||
- **onAbilityStart** - When the ability begins
|
||||
- **onAbilityTick** - Every tick during execution
|
||||
- **onAbilityComplete** - When the ability finishes
|
||||
- **onAbilityDamage** - When the ability deals damage
|
||||
|
||||
Multiple extenders can be registered per ability. Ability scripts are **instanced** — every use gets its own fresh set of variables for optimal performance.
|
||||
|
||||
> 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, projectile visuals, burst patterns, and chained ability sequences 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 prebuilts` - List all built-in abilities
|
||||
- `/kam ability info <name>` - View ability details
|
||||
- `/kam ability delete <name>` - Delete a custom ability
|
||||
- `/kam ability reload` - Reload abilities from disk
|
||||
- `/kam ability give` - Give an ability to a player
|
||||
- `/kam ability remove` - Remove an ability from a player
|
||||
- `/kam ability giveChain` - Give a chained ability to a player
|
||||
- `/kam ability removeChain` - Remove a chained ability from a player
|
||||
- `/kam ability player` - Manage player abilities
|
||||
|
||||
---
|
||||
@@ -1,167 +0,0 @@
|
||||
# 🏪 CustomNPC+ 1.11 - Market Update 🏪
|
||||
|
||||
---
|
||||
|
||||
The **Market Update** brings a complete economy system to CNPC+! Create bustling marketplaces with **Traders** that have limited stock, or let players trade with each other through the brand new **Auction House**!
|
||||
|
||||
---
|
||||
|
||||
## Currency System 💰
|
||||
|
||||
CNPC+ now has a **built-in currency** used across all Market features!
|
||||
|
||||
- **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** - 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.
|
||||
|
||||
---
|
||||
|
||||
## Auction House 🏛️
|
||||
|
||||
A **global player marketplace** where players can list items, bid against each other, and purchase instantly!
|
||||
|
||||
### 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. Auctions last **24 hours** by default with a configurable **minimum listing price**.
|
||||
|
||||
> 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! 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
|
||||
|
||||
See something you need right now? Hit **Buy Now** to purchase instantly at the seller's Buyout Price. If you're currently the highest bidder on an item, you only pay the **difference** between your bid and the buyout.
|
||||
|
||||
### My Trades
|
||||
|
||||
One screen to manage all your auction activity:
|
||||
|
||||
- **Active Listings** - Items you're currently selling
|
||||
- **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. If there are active bids on the listing, a configurable **cancellation penalty** is charged (default 10%).
|
||||
|
||||
> Claims expire after **20 days**. Make sure to collect your items and currency before they're gone!
|
||||
|
||||
### Search & Sorting
|
||||
|
||||
Find what you're looking for with search and sort tools. Search filters by both **item name** and **seller name** simultaneously.
|
||||
|
||||
**Sort Options:**
|
||||
- Newest
|
||||
- Ending Soon
|
||||
- Price (Low to High)
|
||||
- Price (High to Low)
|
||||
- Most Bids
|
||||
|
||||
### Notifications
|
||||
|
||||
Get notified immediately when:
|
||||
- Your item **sells**
|
||||
- You get **outbid**
|
||||
- You **win** an auction
|
||||
- Your auction **expires** with no bids
|
||||
- A **claim is ready** for pickup
|
||||
|
||||
Offline? You'll get a full **claim summary** when you log back in showing exactly what's waiting for you.
|
||||
|
||||
### Trade Slots
|
||||
|
||||
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, or grant **unlimited slots** with the `customnpcs.auction.trades.unlimited` permission.
|
||||
|
||||
---
|
||||
|
||||
## Item Blacklist 🚫
|
||||
|
||||
Server owners have full control over what items can be listed on the Auction House.
|
||||
|
||||
**Block by:**
|
||||
- **Item** - Specific registry names like `minecraft:diamond_sword`
|
||||
- **Wildcard** - Patterns like `minecraft:diamond*` to block all diamond items
|
||||
- **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, regardless of blacklist settings. Bound items cannot be traded!
|
||||
|
||||
**Blacklist Commands:**
|
||||
- `/kam auction blacklist add <item|mod|nbt> <value>` - Add to the blacklist
|
||||
- `/kam auction blacklist remove <item|mod|nbt> <value>` - Remove from the blacklist
|
||||
- `/kam auction blacklist list [item|mod|nbt]` - View blacklisted entries
|
||||
- `/kam auction blacklist reload` - Reload blacklist from config
|
||||
- `/kam auction blacklist check` - Check if your held item is blacklisted
|
||||
|
||||
---
|
||||
|
||||
## Trader Enhancements 🛒
|
||||
|
||||
### Stock System
|
||||
|
||||
Traders now support **limited stock** with automatic restocking!
|
||||
|
||||
**Stock Modes:**
|
||||
- **Global** - All players share the same stock pool
|
||||
- **Per-Player** - Each player has their own purchase limits
|
||||
|
||||
**Restock Timers:**
|
||||
- **MC Daily / Weekly** - Restock based on Minecraft time
|
||||
- **RL Daily / Weekly** - Restock based on real-life time
|
||||
- **Custom** - Set your own interval in MC ticks or real-time
|
||||
|
||||
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!
|
||||
|
||||
---
|
||||
|
||||
## 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 extra configuration needed. The role respects the global Auction Enabled setting.
|
||||
|
||||
---
|
||||
|
||||
## Admin Tools 🔨
|
||||
|
||||
### Admin Auction GUI
|
||||
|
||||
A dedicated management interface for server admins with three tabs:
|
||||
|
||||
- **Listings** - View and search all active auctions. Stop or cancel any listing
|
||||
- **Create** - Create server-managed listings with custom seller names, prices, and durations
|
||||
- **Claims** - Manage the global admin claims pool
|
||||
|
||||
### Auction Commands
|
||||
|
||||
**Player Commands:**
|
||||
- `/kam auction open` - Opens the Auction House GUI
|
||||
|
||||
**Admin Commands:**
|
||||
- `/kam auction list [page]` - View active auctions in chat
|
||||
- `/kam auction view <player>` - 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. Each log type can be toggled individually.
|
||||
|
||||
---
|
||||
|
||||
## Scripting API 📜
|
||||
|
||||
Full event support for auction interactions. All events are **cancelable**, allowing scripts to intercept and control auction behavior:
|
||||
|
||||
- **CreateEvent** - Before an auction is created
|
||||
- **BidEvent** - Before a bid is placed
|
||||
- **BuyoutEvent** - Before an instant purchase
|
||||
- **CancelEvent** - Before a listing is cancelled
|
||||
- **ClaimEvent** - Before a claim is collected
|
||||
|
||||
---
|
||||
@@ -1,95 +1,432 @@
|
||||

|
||||
|
||||
## 👋 Welcome to the CustomNPC+ Repository.
|
||||

|
||||
# CustomNPC+
|
||||
|
||||
> CustomNPC+ is a [Minecraft](https://minecraft.net/) mod that allows you to add custom NPCs to your world. It is developed for creative and storytelling players who want to make their Minecraft worlds more in-depth and unique. CustomNPC+ is only a branch version of the **1.7.10** Forge version of the original (down below) and has no plans to add or update any other version. This is not an official version of CustomNPC.
|
||||
**CustomNPC+** is a Minecraft 1.7.10 Forge mod that lets you create fully customizable NPCs with advanced AI, combat abilities, quests, dialogs, scripting, an economy system, and much more. Built for creative and storytelling players who want to transform their worlds into living RPG experiences.
|
||||
|
||||
----------------
|
||||
> CustomNPC+ is a branch version of the original [CustomNPC](https://www.curseforge.com/minecraft/mc-mods/custom-npcs) by [Noppes](https://github.com/Noppes), developed with permission. This is not an official version of CustomNPC.
|
||||
|
||||
<a href="https://discord.gg/pQqRTvFeJ5"> <img src="https://img.shields.io/badge/KAMKEEL_Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white" width="400" height="60"> </a>
|
||||
<a href="https://ko-fi.com/kamkeel"> <img src="https://img.shields.io/badge/Support_Me_|_Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white" alt="Support Me" width="400" height="60"> </a>
|
||||
---
|
||||
|
||||
<a href="https://discord.gg/pQqRTvFeJ5"> <img src="images/Discord.png" width="400" height="60"> </a>
|
||||
|
||||
[](https://modrinth.com/mod/customnpc-plus)
|
||||
[](https://www.curseforge.com/minecraft/mc-mods/moreplayermodels-plus)
|
||||
[](https://github.com/KAMKEEL/Plugin-Mod)
|
||||
|
||||
----------------
|
||||
---
|
||||
|
||||
### ❗ Notice
|
||||
I am not the original creator of CustomNPC. The original creator is @[Noppes](https://github.com/Noppes). I have been permitted to update and develop my own branch version for 1.7.10. The original mod that is updated to the latest versions of Minecraft can be found on these links: [CurseForge](https://www.curseforge.com/minecraft/mc-mods/custom-npcs), [kodevelopment](http://www.kodevelopment.nl/minecraft/customnpcs)
|
||||
## Installation
|
||||
|
||||
### ⬇️ Downloads
|
||||
CustomNPC+ is a **replacement** for the original CustomNPC — not an add-on. Do not install both together. Simply drop CustomNPC+ into your client or server mods folder. All original CustomNPC features are preserved and expanded upon.
|
||||
|
||||
> Please **backup your world** before installing. Report any bugs on the [issue tracker](https://github.com/KAMKEEL/CustomNPC-Plus/issues).
|
||||
|
||||
### Downloads
|
||||
|
||||
- **Modrinth**: [Download](https://modrinth.com/mod/customnpc-plus)
|
||||
- **CurseForge**: [Download](https://www.curseforge.com/minecraft/mc-mods/customnpc-plus)
|
||||
|
||||
### 🔹 Installation
|
||||
This mod is an ***update*** to CustomNPC and not an add-on. Do not install CustomNPC with CustomNPC-Plus. CustomNPC-Plus does not remove any functional features from the original mod. It expands upon CustomNPC with original features and backported features from newer versions. Simply drag CustomNPC-Plus into any client/server mods folder to utilize. Please **backup** before using as this could still have unforeseen errors. Report any bugs if found, thank you and enjoy.
|
||||
---
|
||||
|
||||
### ❓ Features:
|
||||
- Flying NPC (Smart Pathfinding)
|
||||
- 1.8 Skin Support (64x64) (Alex/Steve64)
|
||||
- Full URL64 Selector (Downloads FULL Size Images for Custom Mob Skins)
|
||||
- Additional Parts: [Wings, Fins, Capes, Horns, Tail]
|
||||
- Hide Body Parts [Arms, Legs, Head, Body]
|
||||
- Custom Overlays
|
||||
- Animation Maker
|
||||
- Enhanced Cloner GUI (More Tabs, Filters, Tags)
|
||||
- Markov Name Generator
|
||||
- Dark Mode GUI (Link Below)
|
||||
- 1.12 Scripting Features (Details below)
|
||||
- Profile System (Multiple Character Slots)
|
||||
- Quest Party System
|
||||
- Item and Armor Attributes
|
||||
- Magic System with Elemental Cycles
|
||||
- Custom Effect Engine
|
||||
- Scripted Blocks & Particles
|
||||
- Compass Marks for Waypoints
|
||||
- Custom Model Support
|
||||
- Gecko & Dragon Block C Addons
|
||||
<a href="https://ko-fi.com/kamkeel"> <img src="images/Kofi.png" width="400" height="60"> </a>
|
||||
|
||||
#### Scripting:
|
||||
- CustomNPC+ Api: [API](https://github.com/KAMKEEL/CustomNPC-Plus-API)
|
||||
- Java Doc: [kamkeel.github.io/CustomNPC-Plus](https://kamkeel.github.io/CustomNPC-Plus/)
|
||||
- Scripted Items
|
||||
- Player Overlays
|
||||
- Script Timers
|
||||
- Global Scripts
|
||||
- Script Logging
|
||||
- GUI Overlays
|
||||
- Event Scripting
|
||||
(We never remove script functionality, only add on existing functions)
|
||||
> More betas with new features will continue to be released to supporters for **Early Access** to new content!
|
||||
|
||||
## 🔰 Skin Model Feature:
|
||||
###### **Majority of these cape designs are taken from the internet with fair-usage.*
|
||||
##### ❔ Please note all *local* skins in this version of CustomNPC, must match the model selected.
|
||||
<img src="images/skinAnimation.gif" width="474" height="260"/>
|
||||
---
|
||||
|
||||
## Feature Overview
|
||||
|
||||
### NPC Creation & Customization
|
||||
|
||||
Create NPCs with deep visual customization and lifelike behavior.
|
||||
|
||||
<img src="images/NPCEditor.gif" width="474" height="260"/>
|
||||
|
||||
- **Skin System** - 1.8 skin support (64x64), Alex & Steve64 models, full URL64 selector that downloads full-size images for custom skins
|
||||
- **Body Parts** - Wings, fins, capes, horns, tails. Hide individual body parts (arms, legs, head, body)
|
||||
- **Skin Overlays** - Layer additional textures on top of the base skin with color tinting and alpha control
|
||||
- **Custom Models** - Support for custom model formats, plus Gecko and DBC addon model integration
|
||||
- **Hitbox Scaling** - Independently scale NPC hitbox width and height
|
||||
- **Tint System** - Control hurt flash color and apply persistent color tints
|
||||
|
||||
---
|
||||
|
||||
### NPC AI & Behavior
|
||||
|
||||
NPCs have a full AI system for combat, pathing, and interaction.
|
||||
|
||||
- **Flying NPCs** - Smart pathfinding in 3D space for flying entities
|
||||
- **Combat AI** - Multiple tactical behaviors: attack, ranged attack, ambush, pounce, dodge-shoot, zigzag, stalk, orbit, sprint-to-target, and leap attacks
|
||||
- **Movement Types** - Standing, wandering, and moving path modes
|
||||
- **Pathfinding** - Ground, flying, and water navigation
|
||||
- **Door Interaction** - NPCs can break, open, or ignore doors
|
||||
- **Behavior Controls** - Configurable sprinting, swimming, fire reactions, tactical chance, and walking range
|
||||
- **Attack Speed** - NPCs respect attack speed timing when dealing damage
|
||||
- **Faction Awareness** - NPCs respond to faction standings. Passive faction NPCs are protected from damage
|
||||
|
||||
#### Flying NPCs:
|
||||
<img src="images/FlyingNPC.gif" width="474" height="260"/>
|
||||
|
||||
#### Url64:
|
||||
<img src="images/Url64Example.gif" width="474" height="260"/>
|
||||
---
|
||||
|
||||
#### DarkMode + Cloner GUI:
|
||||
<img src="images/ClonerGUI-DarkMode.png" width="474" height="260"/>
|
||||
### NPC Roles & Jobs
|
||||
|
||||
## 🔗 Want to check out my other projects?
|
||||
[Plugin Mod](https://github.com/KAMKEEL/Plugin-Mod) is a mod designed to add more aesthetic items for RPG and storytelling. It is compatible with CustomNPC+ and has many items intended to be used and wielded by created NPCs.
|
||||
**Roles** give NPCs interactive functions — Trader, Follower, Bank, Transporter, Postman, Companion, Mount, and Auctioneer. **Jobs** give NPCs background tasks — Bard, Healer, Guard, Item Giver, Follower, Spawner, Conversation, and Chunk Loader.
|
||||
|
||||
[RPG Messenger](https://github.com/KAMKEEL/RPGMessenger) is a bukkit plugin designed to allow operators to create messagable NPCs for RPG Servers. Allows a 'RPG Controller' to reply quickly as NPCs, form groupchats, and messagable parties.
|
||||
---
|
||||
|
||||
[CustomNPC+ Dark Mode](https://github.com/KAMKEEL/CustomNPC-Plus-Dark-Mode) is a resource pack for CustomNPC+ that alters all GUIs within the mod to a dark variant that is both clean and pleasing to look at.
|
||||
### Dialog System
|
||||
|
||||
## Cloning / Compiling / Building
|
||||
Create branching dialog trees for storytelling and player interaction.
|
||||
|
||||
git clone call `git submodule update --init --recursive`
|
||||
<img src="images/Dialog.png" width="474" height="260"/>
|
||||
|
||||
Using IntelliJ, take the following steps:
|
||||
1. Run `setupDecompWorkspace` under the `forgegradle` tab.
|
||||
2. Refresh Gradle.
|
||||
3. Run `genIntellijRuns` under the `other` tab to set up your Minecraft runs.
|
||||
- **Dialog Trees** - Multi-level branching conversations with unlimited depth
|
||||
- **Dialog Options** - Player choices that affect outcomes, trigger quests, or change faction standings
|
||||
- **Dialog Images** - Display images alongside dialog text
|
||||
- **Dialog Colors** - Customizable text and background colors
|
||||
- **Categories** - Organize dialogs into categories for large projects
|
||||
- **Availability Conditions** - Show or hide dialogs based on quests, factions, items, or custom conditions
|
||||
- **Script Hooks** - Full scripting support for dialog open, close, and option events
|
||||
|
||||
or for Eclipse, run `gradlew setupDecompWorkspace eclipse` then import the project.
|
||||
---
|
||||
|
||||
Mixin code will not work if you do not add `--tweakClass org.spongepowered.asm.launch.MixinTweaker --mixin customnpcs.mixins.json` to your program arguments.
|
||||
### Quest System
|
||||
|
||||
A complete quest framework for RPG progression.
|
||||
|
||||
<img src="images/QuestMarks.png" width="474" height="260"/>
|
||||
|
||||
- **Quest Types** - Item collection, dialog completion, kill targets, reach locations, area kills, and fully manual (script-driven) quests
|
||||
- **Quest Tracking** - On-screen HUD overlay showing active quest objectives
|
||||
- **Categories** - Organize quests into categories
|
||||
- **Rewards** - Configure item, XP, and currency rewards
|
||||
- **Cooldowns** - Repeatable quests with MC time, real-time, or custom cooldown intervals
|
||||
- **Party Quests** - Share quest objectives across party members with configurable sharing modes
|
||||
- **Availability** - Control quest visibility based on completed quests, faction standing, dialogs, and more
|
||||
- **Script Hooks** - Events for quest start, completion, turn-in, and custom quest objectives
|
||||
|
||||
---
|
||||
|
||||
### Ability System
|
||||
|
||||
A full combat ability system for both NPCs and players.
|
||||
|
||||
<img src="images/NPCAbilities.gif" width="474" height="260"/>
|
||||
<img src="images/PlayerAbilities.gif" width="474" height="260"/>
|
||||
|
||||
**Melee Abilities** - Slam, Heavy Hit, Cutter
|
||||
**Energy Projectiles** - Orbs, Discs, Beams, Laser Shots with full visual customization, homing, and hit types
|
||||
**Energy Barriers** - Domes, Walls, Shields with HP, reflection, and damage absorption
|
||||
**Defensive** - Guard, Counter, Dodge with configurable damage reduction and counter-attacks
|
||||
**Movement** - Charge, Dash, Teleport
|
||||
**AOE** - Shockwave, Sweeper, Vortex
|
||||
**Hazards & Traps** - Persistent damage zones and proximity-triggered traps with visual presets
|
||||
**Support** - Ability Effect for healing, buffs, and debuffs
|
||||
|
||||
**Key Features:**
|
||||
- Phase-based execution (Wind-up, Active, Dazed) with visual telegraphs
|
||||
- Burst system for rapid multi-fire
|
||||
- Chained abilities for sequential combos
|
||||
- Player ability hotbar (12 slots) with unlock system
|
||||
- Full scripting API for every lifecycle event
|
||||
- Live preview in the ability editor
|
||||
|
||||
---
|
||||
|
||||
### Auction House & Economy
|
||||
|
||||
A complete marketplace and economy system.
|
||||
|
||||
<img src="images/Auction.png" width="474" height="260"/>
|
||||
|
||||
- **Built-in Currency** - Configurable currency with starting balance, max cap, and Vault plugin integration
|
||||
- **Auction House** - Global player marketplace with bidding, buyout, snipe protection, and notifications
|
||||
- **Trade Slots** - Configurable per-player slot limits via permissions
|
||||
- **Item Blacklist** - Block items by name, wildcard, mod, or NBT tag from being listed
|
||||
- **Admin Tools** - Dedicated admin GUI for managing listings and creating server auctions
|
||||
- **Scripting API** - Cancelable events for creates, bids, buyouts, cancels, and claims
|
||||
|
||||
**Trader Enhancements:**
|
||||
- Limited stock with automatic restocking (MC time, real-time, or custom intervals)
|
||||
- Global or per-player stock modes
|
||||
- Currency costs on top of item trades
|
||||
- Client-side balance preview
|
||||
|
||||
---
|
||||
|
||||
### Script Editor
|
||||
|
||||
A full-featured code editor built right into Minecraft.
|
||||
|
||||
<img src="images/ScriptEditor.gif" width="474" height="260"/>
|
||||
|
||||
- **Syntax Highlighting** - Color-coded keywords, types, variables, methods, strings, and comments
|
||||
- **Autocomplete** - Smart suggestions with type awareness, static vs instance context, and auto-imports
|
||||
- **Error Detection** - Real-time underlining of wrong argument types, missing methods, type mismatches, and unused imports
|
||||
- **Hover Info** - Full type information, documentation, and JSDoc rendering on hover
|
||||
- **Navigation** - Go to line, search & replace, go to definition, and fullscreen mode
|
||||
- **Editing** - Smart undo/redo, duplicate lines, comment toggle, rename refactoring, smart bracket pairing
|
||||
- **Visual** - Line numbers, smooth scrolling, indent guides, brace matching, resizable panels
|
||||
|
||||
---
|
||||
|
||||
### Scripting
|
||||
|
||||
Write scripts in **JavaScript** or **Java** to control every aspect of the mod.
|
||||
|
||||
- **Java Scripting** - Write real Java code compiled by the Janino engine. Full support for classes, generics, lambdas, and method references
|
||||
- **JavaScript** - Full Nashorn-based JavaScript with ECMAScript 5.1 globals (Math, JSON, Date, Number)
|
||||
- **Client-Side Scripting** - Run scripts on the client for responsive visual experiences (server-controlled)
|
||||
- **154+ Script Hooks** - Events for NPCs, players, blocks, items, quests, dialogs, factions, abilities, auction, animations, and more
|
||||
- **Script Types** - NPC, Player, Global, Block, Item, Linked Item, Effect, Ability, Recipe, and Forge Event scripts
|
||||
- **Scripted Blocks** - Blocks with full script hooks for click, redstone, neighbor changes, and more
|
||||
- **Scripted Items** - Items with use, attack, toss, pickup, and durability hooks
|
||||
- **Custom GUIs** - Build custom interfaces with buttons, text fields, scroll panels, and slots via scripting
|
||||
- **GUI Overlays** - Persistent on-screen overlays with labels, lines, and textured rectangles
|
||||
- **Addon API** - Mods can ship `.d.ts` type definitions for full autocomplete in the editor
|
||||
|
||||
**Resources:**
|
||||
- API Repository: [CustomNPC+ API](https://github.com/KAMKEEL/CustomNPC-Plus-API)
|
||||
- Java Docs: [kamkeel.github.io/CustomNPC-Plus](https://kamkeel.github.io/CustomNPC-Plus/)
|
||||
|
||||
<img src="images/ScriptedBlock.png" width="474" height="260"/>
|
||||
<img src="images/ScriptedParticle.png" width="474" height="260"/>
|
||||
|
||||
---
|
||||
|
||||
### Animation System
|
||||
|
||||
Create custom animations for NPCs directly in-game.
|
||||
|
||||
- **Animation Maker** - Visual editor for creating frame-based animations
|
||||
- **Animation Parts** - Animate individual body parts with rotation, position, and scaling
|
||||
- **Frame Events** - Script hooks for animation start, end, frame enter, and frame exit
|
||||
- **Data Store** - Animations can store and pass data across events and frames
|
||||
- **Task System** - Consumer-based callbacks for animation lifecycle
|
||||
- **Built-in Animations** - Pre-made animations for abilities that work automatically
|
||||
- **Multiple Registrations** - Register multiple animations under one common name
|
||||
- **Animated Textures** - Frame-based animated textures for items, effects, and ability icons
|
||||
|
||||
<img src="images/AnimationMaker.gif" width="474" height="260"/>
|
||||
|
||||
---
|
||||
|
||||
### Custom Effects
|
||||
|
||||
Create custom status effects beyond vanilla potions.
|
||||
|
||||
- **Custom Icons** - Each effect gets its own texture, with support for animated icons
|
||||
- **Script Hooks** - Events for effect apply, tick, and removal
|
||||
- **Ability Integration** - Abilities can apply custom effects to targets
|
||||
- **Condition System** - Check if entities have specific effects for ability or availability conditions
|
||||
|
||||
---
|
||||
|
||||
### Profile System
|
||||
|
||||
Multiple character slots on a single account.
|
||||
|
||||
- **Profile Slots** - Each slot stores separate quest progress, dialogs, factions, currency, abilities, and effects
|
||||
- **Region Locking** - Lock profiles to specific areas
|
||||
- **Soulbound Items** - Bind items to a specific player by UUID
|
||||
- **Profile-Slotbound Items** - Bind items to a specific profile slot
|
||||
|
||||
---
|
||||
|
||||
### Party System
|
||||
|
||||
Group up with other players for cooperative gameplay.
|
||||
|
||||
- **Party Management** - Invite, kick, leave, disband, and transfer leadership
|
||||
- **Quest Sharing** - Share quest objectives across party members
|
||||
- **Ability Integration** - Party members are treated as allies for AOE ability targeting
|
||||
- **Script Hooks** - Events for invites, kicks, leaves, disbands, and quest completion
|
||||
|
||||
<img src="images/PartySystem.png" width="474" height="260"/>
|
||||
<img src="images/QuestParty.png" width="474" height="260"/>
|
||||
|
||||
---
|
||||
|
||||
### Faction System
|
||||
|
||||
Create factions to control NPC relationships and player reputation.
|
||||
|
||||
- **Faction Points** - Players earn or lose standing with factions through quests, combat, and scripting
|
||||
- **Availability Conditions** - Gate dialogs, quests, and content behind faction thresholds
|
||||
- **NPC Behavior** - NPCs react to players based on faction standing (friendly, neutral, hostile)
|
||||
- **Passive Factions** - Passive faction NPCs are protected from damage
|
||||
|
||||
---
|
||||
|
||||
### HUD System
|
||||
|
||||
Customizable on-screen elements.
|
||||
|
||||
- **HUD Editor** - Drag and position HUD components to fit your screen
|
||||
- **Ability Hotbar** - 12-slot bar with horizontal/vertical layout and configurable visible slots
|
||||
- **Quest Tracking** - On-screen quest objective tracker
|
||||
- **Compass** - Directional compass with quest and waypoint markers
|
||||
- **Effect Bar** - Display active custom effects
|
||||
|
||||
<img src="images/HudSystem.png" width="474" height="260"/>
|
||||
|
||||
---
|
||||
|
||||
### Cloner & Organization
|
||||
|
||||
Save, organize, and reuse NPCs and content.
|
||||
|
||||
- **Cloner Tabs** - Save and load NPCs, items, and other content
|
||||
- **Folder System** - Organize with folders and subfolders for animations, abilities, forms, auras, outlines, effects, and linked items
|
||||
- **Quick Tags** - Tag-based filtering for fast searching
|
||||
- **Full Screen Browser** - Wide directory view for large collections
|
||||
|
||||
<img src="images/ClonerTabs.png" width="474" height="260"/>
|
||||
|
||||
---
|
||||
|
||||
### Items & Blocks
|
||||
|
||||
A large library of custom items and decorative blocks.
|
||||
|
||||
**Weapons:** Battle Axe, Broadsword, Claw, Crossbow, Dagger, Staff, Glaive, Gun, Kunai, Scythe, Spear, Wand, Warhammer, Musket, and more
|
||||
|
||||
**Linked Items:** Create custom items with configurable attack speed, scripted behavior, animated textures, and item versioning
|
||||
|
||||
**Blocks:** Banners, barrels, beams, signs, campfires, candles, chairs, couches, crates, crystals, lanterns, mailboxes, pedestals, redstone blocks, and scripted blocks
|
||||
|
||||
**Crafting:** Carpentry Bench and Anvil with custom recipe support
|
||||
|
||||
<img src="images/VariousWeapons.png" width="474" height="260"/>
|
||||
<img src="images/JappaTextures.png" width="474" height="260"/>
|
||||
|
||||
---
|
||||
|
||||
### Custom Models
|
||||
|
||||
Support for custom NPC models beyond the default humanoid. Import Blockbench models using the **Gecko Addon** (GeckoLib integration) or use **Armorer's Workshop** skins with the AW Addon.
|
||||
|
||||
<img src="images/GeckoAddon1.png" width="474" height="260"/>
|
||||
<img src="images/GeckoAddon2.png" width="474" height="260"/>
|
||||
|
||||
---
|
||||
|
||||
### Addon Compatibility
|
||||
|
||||
CustomNPC+ has official addons that extend its functionality with other mods. Vault and Pixelmon are also supported natively for economy and scripting integration.
|
||||
|
||||
---
|
||||
|
||||
## Official CNPC+ Addons
|
||||
|
||||
### DBC Addon
|
||||
|
||||
Adds full compatibility between [Dragon Block C](https://www.curseforge.com/minecraft/mc-mods/dragon-block-c) and CustomNPC+. Extends abilities with ki-based attacks, adds DBC stat integration to conditions, and enables DBC model/animation support on NPCs.
|
||||
|
||||
[](https://www.curseforge.com/minecraft/mc-mods/cnpc-dbc-addon)
|
||||
[](https://modrinth.com/mod/customnpc-plus-dbc-addon)
|
||||
[](https://github.com/KAMKEEL/CustomNPC-DBC-Addon)
|
||||
|
||||
### Gecko Addon
|
||||
|
||||
Adds [GeckoLib](https://www.curseforge.com/minecraft/mc-mods/geckolib) support to CustomNPC+. Import Blockbench models directly into the mod and use them as custom NPC models with full animation support.
|
||||
|
||||
[](https://www.curseforge.com/minecraft/mc-mods/cnpc-custom-model-addon)
|
||||
[](https://modrinth.com/mod/customnpc-plus-gecko-addon)
|
||||
[](https://github.com/KAMKEEL/CustomNPC-Gecko-Addon)
|
||||
|
||||
### Armorer's Workshop Addon
|
||||
|
||||
Adds compatibility between [Armorer's Workshop](https://www.curseforge.com/minecraft/mc-mods/armorers-workshop) and CustomNPC+. Use Armorer's Workshop skins and equipment on NPCs with custom rotation, scaling, and animation support. Requires UniMixins.
|
||||
|
||||
[](https://www.curseforge.com/minecraft/mc-mods/cnpc-armorers-workshop-addon)
|
||||
[](https://modrinth.com/mod/customnpc-plus-aw-addon)
|
||||
|
||||
---
|
||||
|
||||
## Other Projects
|
||||
|
||||
### MorePlayerModels+
|
||||
|
||||
An updated continuation of MorePlayerModels for 1.7.10 with backported GUIs, original parts and customizations, and permission support. Works alongside CustomNPC+. This is a replacement — do not install alongside the original MorePlayerModels.
|
||||
|
||||
[](https://www.curseforge.com/minecraft/mc-mods/moreplayermodels-plus)
|
||||
[](https://modrinth.com/mod/moreplayermodels+)
|
||||
[](https://github.com/KAMKEEL/MorePlayerModels-Plus)
|
||||
|
||||
### The Plugin Mod
|
||||
|
||||
Adds aesthetic weapons, artifacts, blocks, and apples for RPG and storytelling servers. Designed to pair with CustomNPC+ — use the included swords, spears, axes, medpacks, and decorative blocks to make your NPCs and worlds more diverse.
|
||||
|
||||
[](https://www.curseforge.com/minecraft/mc-mods/the-plugin-mod)
|
||||
[](https://modrinth.com/mod/the-plugin-mod)
|
||||
[](https://github.com/KAMKEEL/Plugin-Mod)
|
||||
|
||||
### HexText
|
||||
|
||||
Upgrades Minecraft's font renderer with full RGB hex color support, nested color spans, and animated text effects (glow, shake, wave). Works in signs, anvils, and chat. Requires UniMixins.
|
||||
|
||||
[](https://www.curseforge.com/minecraft/mc-mods/hex-text)
|
||||
[](https://modrinth.com/mod/hex-text)
|
||||
[](https://github.com/KAMKEEL/HexText)
|
||||
|
||||
### RPG Messenger
|
||||
|
||||
A Bukkit plugin for messageable NPCs, group chats, and RPG controller tools. Allows operators to create NPCs that players can message, and lets RPG controllers reply as NPCs in real-time.
|
||||
|
||||
[](https://github.com/KAMKEEL/RPGMessenger)
|
||||
|
||||
### CustomNPC+ Dark Mode
|
||||
|
||||
A resource pack that applies a clean dark theme to all CustomNPC+ GUIs.
|
||||
|
||||
[](https://github.com/KAMKEEL/CustomNPC-Plus-Dark-Mode)
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
CustomNPC+ has a modular configuration system:
|
||||
|
||||
| Config | Purpose |
|
||||
|--------|---------|
|
||||
| **Main** | Core mod settings |
|
||||
| **Client** | Client-side display and UI preferences |
|
||||
| **Script** | Scripting engine settings and client script toggle |
|
||||
| **Market** | Currency, auction house, trader, and economy settings |
|
||||
| **Energy** | Energy projectile settings (explosion block damage, dome item blacklist) |
|
||||
| **Item** | Item and gun configuration |
|
||||
| **Debug** | Debug logging and diagnostics |
|
||||
| **Experimental** | Experimental features toggle |
|
||||
|
||||
---
|
||||
|
||||
## Building from Source
|
||||
|
||||
This project uses the [GTNH Gradle Convention](https://github.com/GTNewHorizons/ExampleMod1.7.10) build system with [RetroFuturaGradle](https://github.com/GTNewHorizons/RetroFuturaGradle).
|
||||
|
||||
```bash
|
||||
git clone <repo-url>
|
||||
git submodule update --init --recursive
|
||||
./gradlew build
|
||||
```
|
||||
|
||||
That's it. Submodules pull in the API sources, and `build` handles decompilation, compilation, and mixin embedding automatically.
|
||||
|
||||
**Run the game:**
|
||||
```bash
|
||||
./gradlew runClient # Launch client
|
||||
./gradlew runServer # Launch server
|
||||
```
|
||||
|
||||
**IDE Setup (IntelliJ):**
|
||||
1. Import the project as a Gradle project
|
||||
2. Run `./gradlew genIntellijRuns`
|
||||
3. Add program arguments: `--tweakClass org.spongepowered.asm.launch.MixinTweaker --mixin customnpcs.mixins.json`
|
||||
|
||||
---
|
||||
|
||||
## Notice
|
||||
|
||||
I am not the original creator of CustomNPC. The original creator is [Noppes](https://github.com/Noppes). I have been permitted to update and develop my own branch version for 1.7.10. The original mod updated to the latest Minecraft versions can be found on [CurseForge](https://www.curseforge.com/minecraft/mc-mods/custom-npcs) and [kodevelopment](http://www.kodevelopment.nl/minecraft/customnpcs).
|
||||
@@ -43,8 +43,8 @@ dependencies {
|
||||
// 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"))
|
||||
shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.2.jar"))
|
||||
annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.2.jar"))
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 554 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 135 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 114 KiB After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 230 KiB After Width: | Height: | Size: 230 KiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 2.7 MiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 4.0 MiB |
|
Before Width: | Height: | Size: 337 KiB After Width: | Height: | Size: 337 KiB |
|
After Width: | Height: | Size: 573 KiB |
|
Before Width: | Height: | Size: 787 KiB |
|
Before Width: | Height: | Size: 227 KiB After Width: | Height: | Size: 227 KiB |
|
Before Width: | Height: | Size: 2.6 MiB |
|
Before Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 8.0 MiB |
@@ -4,6 +4,7 @@ import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.entity.EntityAbilityBeam;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.renderer.entity.RenderManager;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.util.Vec3;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
@@ -51,21 +52,22 @@ public class RenderEnergyBeam extends RenderEnergy {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get interpolated head offset
|
||||
// Get interpolated head offset (for head/trail rendering relative to origin)
|
||||
double headOffsetX = beam.getInterpolatedHeadOffsetX(partialTicks);
|
||||
double headOffsetY = beam.getInterpolatedHeadOffsetY(partialTicks);
|
||||
double headOffsetZ = beam.getInterpolatedHeadOffsetZ(partialTicks);
|
||||
|
||||
// The render system passes x,y,z as the position to render the entity at
|
||||
// Entity position = origin + headOffset (in world coords)
|
||||
// So origin render position = x,y,z - headOffset
|
||||
double renderOriginX = x - headOffsetX;
|
||||
double renderOriginY = y - headOffsetY;
|
||||
double renderOriginZ = z - headOffsetZ;
|
||||
// Compute render origin directly from the world origin and camera position.
|
||||
// We can't derive it from MC's x,y,z because syncPositionStateToCurrent() snaps
|
||||
// lastTickPos = posX on every sync packet, killing MC's position interpolation.
|
||||
// The headOffset interpolation then mismatches, causing the origin to wobble.
|
||||
double renderOriginX = beam.getOriginX() - RenderManager.renderPosX;
|
||||
double renderOriginY = beam.getOriginY() - RenderManager.renderPosY;
|
||||
double renderOriginZ = beam.getOriginZ() - RenderManager.renderPosZ;
|
||||
|
||||
// Get beam properties
|
||||
float beamWidth = beam.getBeamWidth();
|
||||
float headSize = beam.getHeadSize();
|
||||
// Get beam properties (lerp-smoothed for smooth size transitions)
|
||||
float beamWidth = beam.getInterpolatedBeamWidth(partialTicks);
|
||||
float headSize = beam.getInterpolatedHeadSize(partialTicks);
|
||||
int innerColor = beam.getInnerColor();
|
||||
int outerColor = beam.getOuterColor();
|
||||
float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
|
||||
@@ -77,21 +79,22 @@ public class RenderEnergyBeam extends RenderEnergy {
|
||||
// Calculate head distance from origin (for overlap check)
|
||||
double headDistFromOrigin = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ);
|
||||
|
||||
// Render tail orb at origin (0,0,0) - only in anchored mode
|
||||
// Don't render if head is too close to origin (would cause overlap/extra orb appearance)
|
||||
if (beam.shouldRenderTailOrb() && headDistFromOrigin > headSize * 0.5) {
|
||||
renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, beam.getInnerAlpha() * proximityAlpha);
|
||||
}
|
||||
|
||||
float innerAlpha = beam.getInnerAlpha() * proximityAlpha;
|
||||
|
||||
// Render trail segments with smooth connections (with fading for non-anchored)
|
||||
// Render trail segments first (with fading for non-anchored)
|
||||
if (beam.hasFadingTrail()) {
|
||||
renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
|
||||
} else {
|
||||
renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
|
||||
}
|
||||
|
||||
// Render tail orb at origin (0,0,0) AFTER trail so it draws on top
|
||||
// Don't render if head is too close to origin (would cause overlap/extra orb appearance)
|
||||
// Use target headSize (not lerped) so the threshold isn't inflated by lerp lag
|
||||
if (beam.shouldRenderTailOrb() && headDistFromOrigin > beam.getHeadSize() * 0.5) {
|
||||
renderTailOrb(beam.getHeadSize() * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, innerAlpha);
|
||||
}
|
||||
|
||||
// Render head at interpolated offset position
|
||||
renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks);
|
||||
|
||||
@@ -105,7 +108,7 @@ public class RenderEnergyBeam extends RenderEnergy {
|
||||
* Grows from 0 to headSize based on charge progress.
|
||||
*/
|
||||
private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks, float proximityAlpha) {
|
||||
float headSize = beam.getHeadSize();
|
||||
float headSize = beam.getInterpolatedHeadSize(partialTicks);
|
||||
float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks);
|
||||
float size = headSize * chargeProgress;
|
||||
|
||||
|
||||
@@ -31,8 +31,8 @@ public class RenderEnergyDisc extends RenderEnergy {
|
||||
|
||||
// Get interpolated values
|
||||
float size = disc.getInterpolatedSize(partialTicks);
|
||||
float radius = disc.getDiscRadius() * size;
|
||||
float thickness = disc.getDiscThickness() * size;
|
||||
float radius = disc.getInterpolatedDiscRadius(partialTicks) * size;
|
||||
float thickness = disc.getInterpolatedDiscThickness(partialTicks) * size;
|
||||
|
||||
// Subtle pulsing effect
|
||||
float pulseTime = entity.ticksExisted + partialTicks;
|
||||
|
||||
@@ -43,7 +43,7 @@ public class RenderEnergyLaser extends RenderEnergy {
|
||||
double endX = laser.getInterpolatedEndX(partialTicks);
|
||||
double endY = laser.getInterpolatedEndY(partialTicks);
|
||||
double endZ = laser.getInterpolatedEndZ(partialTicks);
|
||||
float width = laser.getLaserWidth();
|
||||
float width = laser.getInterpolatedLaserWidth(partialTicks);
|
||||
float alpha = 1.0f;
|
||||
|
||||
// Calculate render offset (entity position is used as reference)
|
||||
@@ -156,7 +156,7 @@ public class RenderEnergyLaser extends RenderEnergy {
|
||||
}
|
||||
|
||||
private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) {
|
||||
float headSize = laser.getLaserWidth() * 0.5f;
|
||||
float headSize = laser.getInterpolatedLaserWidth(partialTicks) * 0.5f;
|
||||
float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks);
|
||||
float size = headSize * chargeProgress;
|
||||
|
||||
|
||||
@@ -405,6 +405,8 @@ public class AbilityController implements IAbilityHandler {
|
||||
Ability original = customAbilities.get(originalName);
|
||||
if (original == null || original.isBuiltIn()) return null;
|
||||
|
||||
int originalCatId = customAbilityCatMap.getOrDefault(originalName, CategoryManager.UNCATEGORIZED_ID);
|
||||
|
||||
NBTTagCompound nbt = original.writeNBT(true);
|
||||
nbt.setString("id", UUID.randomUUID().toString());
|
||||
|
||||
@@ -416,6 +418,11 @@ public class AbilityController implements IAbilityHandler {
|
||||
clone.setName(name);
|
||||
|
||||
saveCustomAbility(clone);
|
||||
|
||||
if (originalCatId > CategoryManager.UNCATEGORIZED_ID) {
|
||||
customAbilityCatMap.put(clone.getName(), originalCatId);
|
||||
}
|
||||
|
||||
return clone;
|
||||
}
|
||||
|
||||
@@ -770,6 +777,8 @@ public class AbilityController implements IAbilityHandler {
|
||||
ChainedAbility original = chainedAbilities.get(originalName);
|
||||
if (original == null) return null;
|
||||
|
||||
int originalCatId = chainedAbilityCatMap.getOrDefault(originalName, CategoryManager.UNCATEGORIZED_ID);
|
||||
|
||||
NBTTagCompound nbt = original.writeNBT(true);
|
||||
nbt.setString("Id", UUID.randomUUID().toString());
|
||||
|
||||
@@ -781,6 +790,11 @@ public class AbilityController implements IAbilityHandler {
|
||||
clone.setName(name);
|
||||
|
||||
saveChainedAbility(clone);
|
||||
|
||||
if (originalCatId > CategoryManager.UNCATEGORIZED_ID) {
|
||||
chainedAbilityCatMap.put(clone.getName(), originalCatId);
|
||||
}
|
||||
|
||||
return clone;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,10 +38,16 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
|
||||
FREE_TRAIL
|
||||
}
|
||||
|
||||
// Beam shape properties
|
||||
// Beam shape properties (target values - set by sync packets/scripts)
|
||||
private float beamWidth = 0.3f;
|
||||
private float headSize = 0.5f;
|
||||
|
||||
// Lerp-smoothed render values (approach target each tick)
|
||||
private float renderBeamWidth = 0.3f;
|
||||
private float renderHeadSize = 0.5f;
|
||||
private float prevRenderBeamWidth = 0.3f;
|
||||
private float prevRenderHeadSize = 0.5f;
|
||||
|
||||
// Trail - list of points showing beam path (RELATIVE to origin!)
|
||||
private List<Vec3> trailPoints = new ArrayList<>();
|
||||
private static final int MAX_TRAIL_POINTS = 200;
|
||||
@@ -234,13 +240,23 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
|
||||
|
||||
@Override
|
||||
protected void updateProjectile() {
|
||||
// Save previous render values for sub-tick interpolation
|
||||
prevRenderBeamWidth = renderBeamWidth;
|
||||
prevRenderHeadSize = renderHeadSize;
|
||||
|
||||
// Handle charging state (windup phase) - use isCharging() for synced value
|
||||
if (isCharging()) {
|
||||
// During charging, snap render values to target (size grows smoothly already)
|
||||
renderBeamWidth = beamWidth;
|
||||
renderHeadSize = headSize;
|
||||
updateCharging();
|
||||
return;
|
||||
}
|
||||
|
||||
// Store previous head offset for interpolation
|
||||
// Lerp render values toward target (smooth out sync packet jumps)
|
||||
renderBeamWidth += (beamWidth - renderBeamWidth) * 0.15f;
|
||||
renderHeadSize += (headSize - renderHeadSize) * 0.15f;
|
||||
|
||||
prevHeadOffsetX = headOffsetX;
|
||||
prevHeadOffsetY = headOffsetY;
|
||||
prevHeadOffsetZ = headOffsetZ;
|
||||
@@ -580,6 +596,10 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
|
||||
return beamWidth;
|
||||
}
|
||||
|
||||
public float getInterpolatedBeamWidth(float partialTicks) {
|
||||
return prevRenderBeamWidth + (renderBeamWidth - prevRenderBeamWidth) * partialTicks;
|
||||
}
|
||||
|
||||
public void setBeamWidth(float beamWidth) {
|
||||
this.beamWidth = beamWidth;
|
||||
}
|
||||
@@ -588,6 +608,10 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
|
||||
return headSize;
|
||||
}
|
||||
|
||||
public float getInterpolatedHeadSize(float partialTicks) {
|
||||
return prevRenderHeadSize + (renderHeadSize - prevRenderHeadSize) * partialTicks;
|
||||
}
|
||||
|
||||
public void setHeadSize(float headSize) {
|
||||
this.headSize = headSize;
|
||||
}
|
||||
@@ -758,6 +782,10 @@ public class EntityAbilityBeam extends EntityEnergyProjectile {
|
||||
protected void readProjectileNBT(NBTTagCompound nbt) {
|
||||
this.beamWidth = sanitize(nbt.hasKey("BeamWidth") ? nbt.getFloat("BeamWidth") : 0.3f, 0.3f, MAX_ENTITY_SIZE);
|
||||
this.headSize = sanitize(nbt.hasKey("HeadSize") ? nbt.getFloat("HeadSize") : 0.5f, 0.5f, MAX_ENTITY_SIZE);
|
||||
this.renderBeamWidth = this.beamWidth;
|
||||
this.renderHeadSize = this.headSize;
|
||||
this.prevRenderBeamWidth = this.beamWidth;
|
||||
this.prevRenderHeadSize = this.headSize;
|
||||
this.headOffsetX = nbt.hasKey("HeadOffsetX") ? nbt.getDouble("HeadOffsetX") : 0;
|
||||
this.headOffsetY = nbt.hasKey("HeadOffsetY") ? nbt.getDouble("HeadOffsetY") : 0;
|
||||
this.headOffsetZ = nbt.hasKey("HeadOffsetZ") ? nbt.getDouble("HeadOffsetZ") : 0;
|
||||
|
||||
@@ -30,10 +30,16 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
|
||||
private boolean returning = false;
|
||||
private int ticksSinceMiss = 0;
|
||||
|
||||
// Disc shape properties
|
||||
// Disc shape properties (target values)
|
||||
private float discRadius = 1.0f; // Width of disc
|
||||
private float discThickness = 0.2f; // Height of disc
|
||||
|
||||
// Lerp-smoothed render values
|
||||
private float renderDiscRadius = 1.0f;
|
||||
private float renderDiscThickness = 0.2f;
|
||||
private float prevRenderDiscRadius = 1.0f;
|
||||
private float prevRenderDiscThickness = 0.2f;
|
||||
|
||||
// Boomerang owner-gone tracking
|
||||
private int returnOwnerNullTicks = 0;
|
||||
private boolean vertical = false; // false = horizontal (flat), true = vertical (thin edge forward)
|
||||
@@ -134,12 +140,23 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
|
||||
|
||||
@Override
|
||||
protected void updateProjectile() {
|
||||
// Save previous render values for sub-tick interpolation
|
||||
prevRenderDiscRadius = renderDiscRadius;
|
||||
prevRenderDiscThickness = renderDiscThickness;
|
||||
|
||||
// Handle charging state (windup phase)
|
||||
if (isCharging()) {
|
||||
// During charging, snap render values to target (size grows smoothly already)
|
||||
renderDiscRadius = discRadius;
|
||||
renderDiscThickness = discThickness;
|
||||
updateCharging();
|
||||
return;
|
||||
}
|
||||
|
||||
// Lerp render values toward target (smooth out sync packet jumps)
|
||||
renderDiscRadius += (discRadius - renderDiscRadius) * 0.15f;
|
||||
renderDiscThickness += (discThickness - renderDiscThickness) * 0.15f;
|
||||
|
||||
// In preview mode, run movement on client (no server)
|
||||
if (previewMode) {
|
||||
updatePreviewMovement();
|
||||
@@ -347,6 +364,10 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
|
||||
return discRadius;
|
||||
}
|
||||
|
||||
public float getInterpolatedDiscRadius(float partialTicks) {
|
||||
return prevRenderDiscRadius + (renderDiscRadius - prevRenderDiscRadius) * partialTicks;
|
||||
}
|
||||
|
||||
public void setDiscRadius(float radius) {
|
||||
this.discRadius = radius;
|
||||
}
|
||||
@@ -355,6 +376,10 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
|
||||
return discThickness;
|
||||
}
|
||||
|
||||
public float getInterpolatedDiscThickness(float partialTicks) {
|
||||
return prevRenderDiscThickness + (renderDiscThickness - prevRenderDiscThickness) * partialTicks;
|
||||
}
|
||||
|
||||
public void setDiscThickness(float thickness) {
|
||||
this.discThickness = thickness;
|
||||
}
|
||||
@@ -456,6 +481,10 @@ public class EntityAbilityDisc extends EntityEnergyProjectile {
|
||||
this.boomerangDelay = nbt.hasKey("BoomerangDelay") ? nbt.getInteger("BoomerangDelay") : 40;
|
||||
this.discRadius = sanitize(nbt.hasKey("DiscRadius") ? nbt.getFloat("DiscRadius") : 1.0f, 1.0f, MAX_ENTITY_SIZE);
|
||||
this.discThickness = sanitize(nbt.hasKey("DiscThickness") ? nbt.getFloat("DiscThickness") : 0.2f, 0.2f, MAX_ENTITY_SIZE);
|
||||
this.renderDiscRadius = this.discRadius;
|
||||
this.renderDiscThickness = this.discThickness;
|
||||
this.prevRenderDiscRadius = this.discRadius;
|
||||
this.prevRenderDiscThickness = this.discThickness;
|
||||
this.vertical = nbt.hasKey("Vertical") ? nbt.getBoolean("Vertical") : false;
|
||||
this.returning = nbt.hasKey("Returning") && nbt.getBoolean("Returning");
|
||||
// Charging state (common fields handled by base)
|
||||
|
||||
@@ -31,8 +31,12 @@ import java.util.List;
|
||||
*/
|
||||
public class EntityAbilityLaser extends EntityEnergyProjectile {
|
||||
|
||||
// Laser-specific properties
|
||||
// Laser-specific properties (target value)
|
||||
private float laserWidth = 0.2f;
|
||||
|
||||
// Lerp-smoothed render values
|
||||
private float renderLaserWidth = 0.2f;
|
||||
private float prevRenderLaserWidth = 0.2f;
|
||||
private float expansionSpeed = 2.0f; // Blocks per tick
|
||||
private float maxLength = 32.0f; // Maximum beam reach in blocks
|
||||
|
||||
@@ -144,11 +148,19 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
|
||||
|
||||
@Override
|
||||
protected void updateProjectile() {
|
||||
// Save previous render value for sub-tick interpolation
|
||||
prevRenderLaserWidth = renderLaserWidth;
|
||||
|
||||
if (isCharging()) {
|
||||
// During charging, snap render value to target
|
||||
renderLaserWidth = laserWidth;
|
||||
updateCharging();
|
||||
return;
|
||||
}
|
||||
|
||||
// Lerp render value toward target (smooth out sync packet jumps)
|
||||
renderLaserWidth += (laserWidth - renderLaserWidth) * 0.15f;
|
||||
|
||||
// Save previous positions for partial tick interpolation
|
||||
prevStartX = startX;
|
||||
prevStartY = startY;
|
||||
@@ -703,6 +715,10 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
|
||||
return laserWidth;
|
||||
}
|
||||
|
||||
public float getInterpolatedLaserWidth(float partialTicks) {
|
||||
return prevRenderLaserWidth + (renderLaserWidth - prevRenderLaserWidth) * partialTicks;
|
||||
}
|
||||
|
||||
public void setLaserWidth(float width) {
|
||||
this.laserWidth = width;
|
||||
}
|
||||
@@ -892,6 +908,8 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
|
||||
@Override
|
||||
protected void readProjectileNBT(NBTTagCompound nbt) {
|
||||
this.laserWidth = sanitize(nbt.hasKey("LaserWidth") ? nbt.getFloat("LaserWidth") : 0.2f, 0.2f, MAX_ENTITY_SIZE);
|
||||
this.renderLaserWidth = this.laserWidth;
|
||||
this.prevRenderLaserWidth = this.laserWidth;
|
||||
this.expansionSpeed = sanitize(nbt.hasKey("ExpansionSpeed") ? nbt.getFloat("ExpansionSpeed") : 2.0f, 0.1f, MAX_ENTITY_SIZE);
|
||||
this.maxLength = sanitize(nbt.hasKey("MaxLength") ? nbt.getFloat("MaxLength") : 32.0f, 1.0f, MAX_ENTITY_SIZE);
|
||||
this.dirX = nbt.getDouble("DirX");
|
||||
|
||||
@@ -348,7 +348,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
|
||||
|
||||
// Fire tick event (server-side, non-preview only)
|
||||
if (!previewMode && !worldObj.isRemote) {
|
||||
EventHooks.onEnergyProjectileTick(this);
|
||||
EventHooks.onEnergyProjectileTick(this, ticksExisted);
|
||||
}
|
||||
|
||||
debugLogTick();
|
||||
@@ -738,8 +738,8 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
|
||||
motionY = nbt.getDouble("MotionY");
|
||||
motionZ = nbt.getDouble("MotionZ");
|
||||
syncPositionStateToCurrent(true);
|
||||
// Size & visual
|
||||
setProjectileSize(nbt.getFloat("Size"));
|
||||
// Size & visual (set target only - let the lerp in onUpdate smooth the transition)
|
||||
this.size = nbt.getFloat("Size");
|
||||
displayData.setRotationSpeed(nbt.getFloat("RotationSpeed"));
|
||||
displayData.setInnerAlpha(nbt.getFloat("InnerAlpha"));
|
||||
displayData.setOuterColorEnabled(nbt.getBoolean("OuterColorEnabled"));
|
||||
|
||||
@@ -101,12 +101,14 @@ import kamkeel.npcs.network.packets.request.category.CategoryListRequestPacket;
|
||||
import kamkeel.npcs.network.packets.request.category.CategoryMoveItemPacket;
|
||||
import kamkeel.npcs.network.packets.request.category.CategoryRemovePacket;
|
||||
import kamkeel.npcs.network.packets.request.category.CategorySavePacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.CopyAbilityScriptsPacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.CustomAbilityClonePacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.CustomAbilityGetPacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.CustomAbilityRemovePacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.CustomAbilitySavePacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationClonePacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationSavePacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.BuiltInAnimationGetPacket;
|
||||
@@ -498,6 +500,7 @@ public class PacketHandler {
|
||||
REQUEST_PACKET.registerPacket(new AnimationGetPacket());
|
||||
REQUEST_PACKET.registerPacket(new AnimationRemovePacket());
|
||||
REQUEST_PACKET.registerPacket(new AnimationSavePacket());
|
||||
REQUEST_PACKET.registerPacket(new AnimationClonePacket());
|
||||
REQUEST_PACKET.registerPacket(new BuiltInAnimationGetPacket());
|
||||
|
||||
// Moving Path
|
||||
@@ -541,6 +544,7 @@ public class PacketHandler {
|
||||
REQUEST_PACKET.registerPacket(new ChainedAbilityRemovePacket());
|
||||
REQUEST_PACKET.registerPacket(new CustomAbilityClonePacket());
|
||||
REQUEST_PACKET.registerPacket(new ChainedAbilityClonePacket());
|
||||
REQUEST_PACKET.registerPacket(new CopyAbilityScriptsPacket());
|
||||
|
||||
// Category Packets
|
||||
REQUEST_PACKET.registerPacket(new CategorySavePacket());
|
||||
|
||||
@@ -93,6 +93,7 @@ public enum EnumRequestPacket {
|
||||
AnimationGet,
|
||||
AnimationRemove,
|
||||
AnimationSave,
|
||||
AnimationClone,
|
||||
BuiltInAnimationGet,
|
||||
|
||||
RemoteNpcsGet,
|
||||
@@ -226,6 +227,7 @@ public enum EnumRequestPacket {
|
||||
|
||||
CustomAbilityClone,
|
||||
ChainedAbilityClone,
|
||||
CopyAbilityScripts,
|
||||
LinkedItemClone,
|
||||
EffectClone,
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package kamkeel.npcs.network.packets.request.ability;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import kamkeel.npcs.controllers.AbilityController;
|
||||
import kamkeel.npcs.controllers.data.ability.Ability;
|
||||
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
|
||||
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.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.data.AbilityScript;
|
||||
import noppes.npcs.controllers.data.ChainedAbilityScript;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Copies script data from a source ability/chain to a target UUID.
|
||||
* Used when cloning into an NPC as inline - the clone gets a new UUID
|
||||
* but needs the source's script handler copied server-side (scripts are never sent to client).
|
||||
*
|
||||
* Mode 0 = ability scripts, Mode 1 = chained ability scripts.
|
||||
*/
|
||||
public final class CopyAbilityScriptsPacket extends AbstractPacket {
|
||||
public static String packetName = "Request|CopyAbilityScripts";
|
||||
|
||||
public static final int MODE_ABILITY = 0;
|
||||
public static final int MODE_CHAINED = 1;
|
||||
|
||||
private int mode;
|
||||
private String sourceName;
|
||||
private String targetId;
|
||||
|
||||
public CopyAbilityScriptsPacket() {
|
||||
}
|
||||
|
||||
public CopyAbilityScriptsPacket(String sourceName, String targetId) {
|
||||
this(MODE_ABILITY, sourceName, targetId);
|
||||
}
|
||||
|
||||
public CopyAbilityScriptsPacket(int mode, String sourceName, String targetId) {
|
||||
this.mode = mode;
|
||||
this.sourceName = sourceName;
|
||||
this.targetId = targetId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enum getType() {
|
||||
return EnumRequestPacket.CopyAbilityScripts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketChannel getChannel() {
|
||||
return PacketHandler.REQUEST_PACKET;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomNpcsPermissions.Permission getPermission() {
|
||||
return CustomNpcsPermissions.GLOBAL_ABILITY;
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void sendData(ByteBuf out) throws IOException {
|
||||
out.writeByte(mode);
|
||||
ByteBufUtils.writeString(out, sourceName);
|
||||
ByteBufUtils.writeString(out, targetId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
|
||||
if (!(player instanceof EntityPlayerMP))
|
||||
return;
|
||||
|
||||
if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player))
|
||||
return;
|
||||
|
||||
int mode = in.readByte();
|
||||
String sourceName = ByteBufUtils.readString(in);
|
||||
String targetId = ByteBufUtils.readString(in);
|
||||
|
||||
if (targetId == null || targetId.isEmpty()) return;
|
||||
|
||||
if (mode == MODE_CHAINED) {
|
||||
copyChainedAbilityScripts(sourceName, targetId);
|
||||
} else {
|
||||
copyAbilityScripts(sourceName, targetId);
|
||||
}
|
||||
}
|
||||
|
||||
private void copyAbilityScripts(String sourceKey, String targetId) {
|
||||
// Try name-based lookup first
|
||||
Ability source = AbilityController.Instance.getCustomAbility(sourceKey);
|
||||
|
||||
AbilityScript sourceHandler;
|
||||
if (source != null) {
|
||||
sourceHandler = source.getScriptHandler();
|
||||
} else {
|
||||
// sourceKey might be a UUID - try direct handler lookup
|
||||
sourceHandler = AbilityController.Instance.abilityScriptHandlers.get(sourceKey);
|
||||
}
|
||||
if (sourceHandler == null) return;
|
||||
|
||||
NBTTagCompound scriptNbt = sourceHandler.writeToNBT(new NBTTagCompound());
|
||||
AbilityScript targetHandler = new AbilityScript(targetId);
|
||||
targetHandler.readFromNBT(scriptNbt);
|
||||
AbilityController.Instance.abilityScriptHandlers.put(targetId, targetHandler);
|
||||
}
|
||||
|
||||
private void copyChainedAbilityScripts(String sourceName, String targetId) {
|
||||
ChainedAbility source = AbilityController.Instance.getChainedAbility(sourceName);
|
||||
if (source == null) return;
|
||||
|
||||
ChainedAbilityScript sourceHandler = source.getScriptHandler();
|
||||
if (sourceHandler == null) return;
|
||||
|
||||
NBTTagCompound scriptNbt = sourceHandler.writeToNBT(new NBTTagCompound());
|
||||
ChainedAbilityScript targetHandler = new ChainedAbilityScript(targetId);
|
||||
targetHandler.readFromNBT(scriptNbt);
|
||||
AbilityController.Instance.chainedAbilityScriptHandlers.put(targetId, targetHandler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package kamkeel.npcs.network.packets.request.animation;
|
||||
|
||||
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 noppes.npcs.CustomNpcsPermissions;
|
||||
import noppes.npcs.NoppesUtilServer;
|
||||
import noppes.npcs.controllers.AnimationController;
|
||||
import noppes.npcs.controllers.data.Animation;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public final class AnimationClonePacket extends AbstractPacket {
|
||||
public static String packetName = "Request|AnimationClone";
|
||||
|
||||
private int id;
|
||||
|
||||
public AnimationClonePacket() {
|
||||
}
|
||||
|
||||
public AnimationClonePacket(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enum getType() {
|
||||
return EnumRequestPacket.AnimationClone;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketChannel getChannel() {
|
||||
return PacketHandler.REQUEST_PACKET;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CustomNpcsPermissions.Permission getPermission() {
|
||||
return CustomNpcsPermissions.GLOBAL_ANIMATION;
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void sendData(ByteBuf out) throws IOException {
|
||||
out.writeInt(this.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
|
||||
if (!(player instanceof EntityPlayerMP))
|
||||
return;
|
||||
if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player))
|
||||
return;
|
||||
|
||||
int animationId = in.readInt();
|
||||
Animation clone = AnimationController.getInstance().cloneAnimation(animationId);
|
||||
if (clone != null) {
|
||||
NoppesUtilServer.sendAnimationDataAll((EntityPlayerMP) player);
|
||||
GuiDataPacket.sendGuiData((EntityPlayerMP) player, clone.writeToNBT());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,7 @@ import noppes.npcs.compat.PixelmonHelper;
|
||||
import noppes.npcs.config.ConfigMain;
|
||||
import noppes.npcs.config.LoadConfiguration;
|
||||
import noppes.npcs.config.legacy.LegacyConfig;
|
||||
import noppes.npcs.controllers.APIRegistry;
|
||||
import noppes.npcs.controllers.AnimationController;
|
||||
import noppes.npcs.controllers.AuctionController;
|
||||
import noppes.npcs.controllers.BankController;
|
||||
@@ -316,6 +317,8 @@ public class CustomNpcs {
|
||||
new AddonManager();
|
||||
new AttributeController();
|
||||
new MagicController();
|
||||
|
||||
APIRegistry.Instance.register("CNPC+ API", "https://kamkeel.github.io/CustomNPC-Plus/");
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
|
||||
@@ -482,9 +482,9 @@ public class EventHooks {
|
||||
NpcAPI.EVENT_BUS.post(event);
|
||||
}
|
||||
|
||||
public static void onEnergyProjectileTick(EntityEnergyProjectile projectile) {
|
||||
public static void onEnergyProjectileTick(EntityEnergyProjectile projectile, int tick) {
|
||||
IEnergyProjectile wrapped = (IEnergyProjectile) NpcAPI.Instance().getIEntity(projectile);
|
||||
EnergyProjectileEvent.UpdateEvent event = new EnergyProjectileEvent.UpdateEvent(wrapped);
|
||||
EnergyProjectileEvent.UpdateEvent event = new EnergyProjectileEvent.UpdateEvent(wrapped, tick);
|
||||
ScriptController.Instance.globalNpcScripts.callScript(EnumScriptType.ENERGY_PROJECTILE_TICK, event);
|
||||
|
||||
Entity owner = projectile.worldObj.getEntityByID(projectile.getOwnerEntityId());
|
||||
|
||||
@@ -2,13 +2,15 @@ package noppes.npcs.client.gui;
|
||||
|
||||
import kamkeel.npcs.network.packets.request.script.NPCScriptPacket;
|
||||
import net.minecraft.client.gui.GuiButton;
|
||||
import net.minecraft.client.gui.GuiConfirmOpenLink;
|
||||
import net.minecraft.client.gui.GuiYesNo;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.StatCollector;
|
||||
import noppes.npcs.NoppesStringUtils;
|
||||
import noppes.npcs.client.NoppesUtil;
|
||||
import noppes.npcs.client.gui.util.SubGuiAPISelect;
|
||||
import noppes.npcs.client.gui.util.SubGuiConfirmLink;
|
||||
import noppes.npcs.controllers.APIRegistry;
|
||||
import noppes.npcs.client.gui.script.GuiScriptInterface;
|
||||
import noppes.npcs.client.gui.util.GuiCustomScroll;
|
||||
import noppes.npcs.client.gui.util.GuiMenuTopButton;
|
||||
@@ -107,7 +109,7 @@ public class GuiScript extends GuiScriptInterface {
|
||||
top.active = showScript;
|
||||
addTopButton(top = new GuiMenuTopButton(14, top, "gui.settings"));
|
||||
top.active = !showScript;
|
||||
addTopButton(new GuiMenuTopButton(15, top, "gui.website"));
|
||||
addTopButton(new GuiMenuTopButton(15, top, "gui.api"));
|
||||
|
||||
if (showScript) {
|
||||
initScriptView();
|
||||
@@ -285,9 +287,6 @@ public class GuiScript extends GuiScriptInterface {
|
||||
NoppesUtil.openGUI(player, this);
|
||||
if (!result)
|
||||
return;
|
||||
if (id == 0) {
|
||||
openLink("https://kamkeel.github.io/CustomNPC-Plus/");
|
||||
}
|
||||
if (id == 101) {
|
||||
getTextField(2).setText(NoppesStringUtils.getClipboardContents());
|
||||
}
|
||||
@@ -319,7 +318,12 @@ public class GuiScript extends GuiScriptInterface {
|
||||
initGui();
|
||||
}
|
||||
if (guibutton.id == 15) {
|
||||
displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
|
||||
if (APIRegistry.Instance.size() == 1) {
|
||||
String url = APIRegistry.Instance.getEntries().values().iterator().next();
|
||||
setSubGui(new SubGuiConfirmLink(url));
|
||||
} else {
|
||||
setSubGui(new SubGuiAPISelect());
|
||||
}
|
||||
}
|
||||
if (guibutton.id == 16) {
|
||||
close();
|
||||
|
||||
@@ -7,6 +7,7 @@ import kamkeel.npcs.controllers.data.ability.AbilityVariant;
|
||||
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
|
||||
import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
|
||||
import kamkeel.npcs.network.PacketClient;
|
||||
import kamkeel.npcs.network.packets.request.ability.CopyAbilityScriptsPacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.AbilitiesGetAllPacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcGetPacket;
|
||||
import kamkeel.npcs.network.packets.request.ability.AbilitiesNpcSavePacket;
|
||||
@@ -816,6 +817,14 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
|
||||
* Adds as an inline slot.
|
||||
*/
|
||||
public void loadAbility(Ability loadedAbility) {
|
||||
loadAbility(loadedAbility, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from SubGuiAbilityLoad when a cloned ability is loaded with a known source.
|
||||
* Copies scripts server-side from source to the new inline ability.
|
||||
*/
|
||||
public void loadAbility(Ability loadedAbility, String sourceAbilityName) {
|
||||
if (loadedAbility != null) {
|
||||
loadedAbility.setId(UUID.randomUUID().toString());
|
||||
npcSlots.add(AbilityAction.inline(loadedAbility));
|
||||
@@ -825,6 +834,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
|
||||
selectAbilityByIndex(selectedAbilityIndex);
|
||||
initGui();
|
||||
save();
|
||||
// Copy scripts from source ability server-side (scripts are never sent to client)
|
||||
if (sourceAbilityName != null && !sourceAbilityName.isEmpty()) {
|
||||
PacketClient.sendClient(new CopyAbilityScriptsPacket(sourceAbilityName, loadedAbility.getId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -981,12 +994,18 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
|
||||
if (slot.isChain() && selectedEntryIndex == -1) {
|
||||
// Chain header (must be CHAIN_REFERENCE)
|
||||
if (mode == SubGuiAbilityEditMode.MODE_CLONE_MODIFY) {
|
||||
String sourceChainName = slot.getReferenceId();
|
||||
if (slot.convertToInline()) {
|
||||
ChainedAbility chain = slot.getInlineChain();
|
||||
if (chain != null) {
|
||||
pendingChain = chain;
|
||||
pendingChainSlotIdx = selectedSlotIndex;
|
||||
setSubGui(new SubGuiChainedAbilityConfig(chain, this, true, npcSlots));
|
||||
// Copy chain scripts server-side (client never has script handlers)
|
||||
if (sourceChainName != null && !sourceChainName.isEmpty()) {
|
||||
PacketClient.sendClient(new CopyAbilityScriptsPacket(
|
||||
CopyAbilityScriptsPacket.MODE_CHAINED, sourceChainName, chain.getId()));
|
||||
}
|
||||
}
|
||||
updateNpcAbilitiesList();
|
||||
save();
|
||||
@@ -1015,6 +1034,8 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
|
||||
ChainedAbility chain = slot.getInlineChain();
|
||||
if (chain != null && selectedEntryIndex < chain.getEntries().size()) {
|
||||
ChainedAbilityEntry entry = chain.getEntries().get(selectedEntryIndex);
|
||||
// Capture source ability reference before convertToInline clears it
|
||||
String sourceAbilityRef = entry.getAbilityReference();
|
||||
if (entry.convertToInline()) {
|
||||
Ability a = entry.getInlineAbility();
|
||||
if (a != null && !a.isBuiltIn()) {
|
||||
@@ -1023,6 +1044,10 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
|
||||
editChainEntryIdx = selectedEntryIndex;
|
||||
a.setNpcInlineEdit(true);
|
||||
setSubGui(a.createConfigGui(this));
|
||||
// Copy ability scripts server-side (client never has script handlers)
|
||||
if (sourceAbilityRef != null && !sourceAbilityRef.isEmpty()) {
|
||||
PacketClient.sendClient(new CopyAbilityScriptsPacket(sourceAbilityRef, a.getId()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1043,12 +1068,18 @@ public class GuiNPCAbilities extends GuiNPCInterface2 implements IScrollData, IC
|
||||
// Standalone ability reference → convert to inline
|
||||
Ability preCheck = slot.getAbility();
|
||||
if (preCheck != null && preCheck.isBuiltIn()) return;
|
||||
// Capture source reference before convertToInline clears it
|
||||
String sourceAbilityRef = slot.getReferenceId();
|
||||
if (slot.convertToInline()) {
|
||||
Ability ability = slot.getAbility();
|
||||
if (ability != null && !ability.isBuiltIn()) {
|
||||
ability.setId(UUID.randomUUID().toString());
|
||||
// UUID already generated by convertToInline() - don't reassign or script handler is orphaned
|
||||
ability.setNpcInlineEdit(true);
|
||||
setSubGui(ability.createConfigGui(this));
|
||||
// Copy ability scripts server-side (client never has script handlers)
|
||||
if (sourceAbilityRef != null && !sourceAbilityRef.isEmpty()) {
|
||||
PacketClient.sendClient(new CopyAbilityScriptsPacket(sourceAbilityRef, ability.getId()));
|
||||
}
|
||||
}
|
||||
updateNpcAbilitiesList();
|
||||
save();
|
||||
|
||||
@@ -216,7 +216,7 @@ public class SubGuiAbilityLoad extends SubGuiInterface implements ICustomScrollL
|
||||
if (parentConfig != null) {
|
||||
parentConfig.loadAbility(loaded);
|
||||
} else if (parentAbilities != null) {
|
||||
parentAbilities.loadAbility(loaded);
|
||||
parentAbilities.loadAbility(loaded, selectedName);
|
||||
}
|
||||
}
|
||||
close();
|
||||
|
||||
@@ -3,6 +3,7 @@ package noppes.npcs.client.gui.global;
|
||||
import kamkeel.npcs.network.PacketClient;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationGetPacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationRemovePacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationClonePacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationSavePacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.AnimationsGetPacket;
|
||||
import kamkeel.npcs.network.packets.request.animation.BuiltInAnimationGetPacket;
|
||||
@@ -169,11 +170,7 @@ public class GuiAnimationDirectory extends GuiDirectoryCategorized {
|
||||
protected void onCloneItem() {
|
||||
if (showingBuiltIn || currentIsBuiltIn) return;
|
||||
if (animation != null && animation.id >= 0) {
|
||||
Animation clone = new Animation();
|
||||
clone.readFromNBT(animation.writeToNBT());
|
||||
clone.id = -1;
|
||||
while (itemData.containsKey(clone.name)) clone.name += "_";
|
||||
PacketClient.sendClient(new AnimationSavePacket(clone.writeToNBT()));
|
||||
PacketClient.sendClient(new AnimationClonePacket(animation.id));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ public class GuiHudEditor extends GuiScreen {
|
||||
|
||||
private final int HANDLE_SIZE = 10;
|
||||
private final int RESET_POSITION_ID = 100;
|
||||
private final int RESET_SIZE_ID = 104;
|
||||
|
||||
// IDs for cycle buttons.
|
||||
private final int CYCLE_LEFT_ID = 101;
|
||||
@@ -90,9 +91,11 @@ public class GuiHudEditor extends GuiScreen {
|
||||
rowHeight += btn.height + spacingY;
|
||||
}
|
||||
}
|
||||
// Always add the Reset Position button below the custom buttons.
|
||||
GuiButton resetPos = new GuiButton(RESET_POSITION_ID, width / 2 - buttonWidth / 2, height - 70 - rowHeight, buttonWidth, 20, "Reset Position");
|
||||
// Always add the Reset Position and Reset Size buttons below the custom buttons.
|
||||
GuiButton resetSize = new GuiButton(RESET_SIZE_ID, startXRight, height - 70 - rowHeight, buttonWidth, 20, "Reset Size");
|
||||
GuiButton resetPos = new GuiButton(RESET_POSITION_ID, startXLeft, height - 70 - rowHeight, buttonWidth, 20, "Reset Position");
|
||||
buttonList.add(resetPos);
|
||||
buttonList.add(resetSize);
|
||||
}
|
||||
|
||||
// Now update (or add if missing) the cycle buttons at the very bottom.
|
||||
@@ -149,10 +152,11 @@ public class GuiHudEditor extends GuiScreen {
|
||||
int actualY = (int) (hud.posY / 100F * res.getScaledHeight());
|
||||
int margin = 5;
|
||||
int barWidth = 6; // same as WIDTH_BAR_SIZE
|
||||
int barX = actualX + (int) (hud.overlayWidth * effectiveScale) + margin;
|
||||
int barX = actualX + (int) ((hud.overlayWidth + margin) * effectiveScale);
|
||||
int barY = actualY + (int) (((hud.overlayHeight - 20) / 2.0F) * effectiveScale);
|
||||
int barHeight = (int) (20 * effectiveScale);
|
||||
if (mouseX >= barX && mouseX <= barX + barWidth &&
|
||||
int scaledBarWidth = Math.max(6, (int) (barWidth * effectiveScale));
|
||||
if (mouseX >= barX && mouseX <= barX + scaledBarWidth &&
|
||||
mouseY >= barY && mouseY <= barY + barHeight) {
|
||||
resizingWidth = true;
|
||||
selectedComponent = hud;
|
||||
@@ -226,15 +230,22 @@ public class GuiHudEditor extends GuiScreen {
|
||||
}
|
||||
if (resizing) {
|
||||
int currentMouseX = Mouse.getX() * width / mc.displayWidth;
|
||||
int deltaX = currentMouseX - initialMouseX;
|
||||
selectedComponent.scale = initialScale + deltaX;
|
||||
int currentMouseY = scaledHeight - (Mouse.getY() * scaledHeight / mc.displayHeight);
|
||||
int actualX = (int) (selectedComponent.posX / 100F * scaledWidth);
|
||||
int actualY = (int) (selectedComponent.posY / 100F * scaledHeight);
|
||||
// Use diagonal distance ratio so the resize handle tracks the mouse
|
||||
float initDist = (float) Math.sqrt((double)(initialMouseX - actualX) * (initialMouseX - actualX) + (double)(initialMouseY - actualY) * (initialMouseY - actualY));
|
||||
float currDist = (float) Math.sqrt((double)(currentMouseX - actualX) * (currentMouseX - actualX) + (double)(currentMouseY - actualY) * (currentMouseY - actualY));
|
||||
if (initDist > 1) {
|
||||
selectedComponent.scale = (int) (initialScale * currDist / initDist);
|
||||
}
|
||||
if (selectedComponent.scale < 50) selectedComponent.scale = 50;
|
||||
if (selectedComponent.scale > 300) selectedComponent.scale = 300;
|
||||
if (selectedComponent.scale > 500) selectedComponent.scale = 500;
|
||||
}
|
||||
if (resizingWidth && (selectedComponent instanceof CompassHudComponent)) {
|
||||
int currentMouseX = Mouse.getX() * width / mc.displayWidth;
|
||||
int delta = currentMouseX - initialWidthMouseX;
|
||||
selectedComponent.overlayWidth = initialOverlayWidth + delta;
|
||||
selectedComponent.overlayWidth = initialOverlayWidth + (int) (delta / effectiveScale);
|
||||
if (selectedComponent.overlayWidth < 50) selectedComponent.overlayWidth = 50;
|
||||
if (selectedComponent.overlayWidth > 500) selectedComponent.overlayWidth = 500;
|
||||
}
|
||||
@@ -267,6 +278,11 @@ public class GuiHudEditor extends GuiScreen {
|
||||
selectedComponent.posY = 100F * centerY / res.getScaledHeight();
|
||||
updateCustomButtons();
|
||||
}
|
||||
} else if (button.id == RESET_SIZE_ID) {
|
||||
if (selectedComponent != null) {
|
||||
selectedComponent.scale = 100;
|
||||
updateCustomButtons();
|
||||
}
|
||||
} else if (button.id == CYCLE_LEFT_ID) {
|
||||
cycleComponent(-1);
|
||||
} else if (button.id == CYCLE_RIGHT_ID) {
|
||||
|
||||
@@ -1,429 +0,0 @@
|
||||
package noppes.npcs.client.gui.script;
|
||||
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiButton;
|
||||
import net.minecraft.client.gui.GuiConfirmOpenLink;
|
||||
import net.minecraft.client.gui.GuiScreen;
|
||||
import net.minecraft.client.gui.GuiYesNo;
|
||||
import net.minecraft.client.gui.GuiYesNoCallback;
|
||||
import net.minecraft.util.StatCollector;
|
||||
import noppes.npcs.NoppesStringUtils;
|
||||
import noppes.npcs.client.gui.util.GuiCustomScroll;
|
||||
import noppes.npcs.client.gui.util.GuiMenuTopButton;
|
||||
import noppes.npcs.client.gui.util.GuiNPCInterface;
|
||||
import noppes.npcs.client.gui.util.GuiNpcButton;
|
||||
import noppes.npcs.client.gui.util.GuiNpcLabel;
|
||||
import noppes.npcs.client.gui.util.GuiNpcTextArea;
|
||||
import noppes.npcs.client.gui.util.GuiScriptTextArea;
|
||||
import noppes.npcs.client.gui.util.ICustomScrollListener;
|
||||
import noppes.npcs.client.gui.util.ISubGuiListener;
|
||||
import noppes.npcs.client.gui.util.ITextChangeListener;
|
||||
import noppes.npcs.client.gui.util.SubGuiInterface;
|
||||
import noppes.npcs.controllers.ScriptController;
|
||||
import noppes.npcs.janino.JaninoScript;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class GuiJaninoScript extends GuiNPCInterface implements GuiYesNoCallback, ITextChangeListener, ICustomScrollListener, ISubGuiListener {
|
||||
|
||||
private GuiScriptTextArea textArea;
|
||||
private int activeTab = 0;
|
||||
public List<String> allExternalScripts = new ArrayList<>();
|
||||
private final int scriptLimit = 1;
|
||||
public String previousHookClicked = "";
|
||||
|
||||
// GUI display list
|
||||
List<String> hooklist = new ArrayList<>();
|
||||
|
||||
// Map from display name (with parameters if overloaded) to Method
|
||||
Map<String, Method> hookMap = new HashMap<>();
|
||||
|
||||
public final GuiScreen parent;
|
||||
private final JaninoScript container;
|
||||
|
||||
public Runnable saveFunction;
|
||||
|
||||
public GuiJaninoScript(GuiScreen parent, JaninoScript handler) {
|
||||
this.drawDefaultBackground = true;
|
||||
this.closeOnEsc = true;
|
||||
this.xSize = 420;
|
||||
this.setBackground("menubg.png");
|
||||
|
||||
this.parent = parent;
|
||||
this.container = handler;
|
||||
|
||||
createHookList();
|
||||
|
||||
String lang = handler.getLanguage();
|
||||
allExternalScripts.addAll(ScriptController.Instance.getScripts(lang));
|
||||
}
|
||||
|
||||
public GuiJaninoScript setSave(Runnable run) {
|
||||
saveFunction = run;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void createHookList() {
|
||||
// Group all declared methods of the handler's type by their method name
|
||||
Map<String, List<Method>> grouped = Arrays.stream(container.type.getDeclaredMethods())
|
||||
.collect(Collectors.groupingBy(Method::getName));
|
||||
|
||||
for (Map.Entry<String, List<Method>> entry : grouped.entrySet()) {
|
||||
List<Method> methods = entry.getValue();
|
||||
|
||||
// Sort overloads by number of parameters (ascending)
|
||||
// This ensures the simplest overload comes first
|
||||
methods.sort(Comparator.comparingInt(Method::getParameterCount));
|
||||
boolean first = true;
|
||||
|
||||
|
||||
for (Method m : methods) {
|
||||
if (Modifier.isFinal(m.getModifiers()))
|
||||
continue; //skip finals
|
||||
|
||||
String displayName = first ? m.getName() :
|
||||
m.getName() + "(" + Arrays.stream(m.getParameterTypes())
|
||||
.map(Class::getSimpleName)
|
||||
.collect(Collectors.joining(", ")) + ")";
|
||||
|
||||
|
||||
hooklist.add(displayName);
|
||||
hookMap.put(displayName, m);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void initGui() {
|
||||
this.ySize = (int) ((double) this.xSize * 0.56);
|
||||
if ((double) this.ySize > (double) this.height * 0.95) {
|
||||
this.ySize = (int) ((double) this.height * 0.95);
|
||||
this.xSize = (int) ((double) this.ySize / 0.56);
|
||||
}
|
||||
|
||||
this.bgScale = (float) this.xSize / 400.0F;
|
||||
super.initGui();
|
||||
this.guiTop += 10;
|
||||
int yoffset = (int) ((double) this.ySize * 0.02);
|
||||
GuiMenuTopButton top;
|
||||
addTopButton(new GuiMenuTopButton(-1, guiLeft + xSize - 2, guiTop - 17, "X"));
|
||||
this.addTopButton(top = new GuiMenuTopButton(0, this.guiLeft + 4, this.guiTop - 17, "gui.settings"));
|
||||
int topXoffset = 0;
|
||||
int topYoffset = 0;
|
||||
|
||||
|
||||
if (this.container != null) {
|
||||
this.addTopButton(top = new GuiMenuTopButton(1, top.xPosition + top.width + topXoffset, top.yPosition + topYoffset, "Script"));
|
||||
} else {
|
||||
this.addTopButton(new GuiMenuTopButton(this.scriptLimit, top.xPosition + top.width, top.yPosition, "+"));
|
||||
}
|
||||
|
||||
top = this.getTopButton(this.activeTab);
|
||||
if (top == null) {
|
||||
this.activeTab = 0;
|
||||
top = this.getTopButton(0);
|
||||
}
|
||||
|
||||
top.active = true;
|
||||
if (this.activeTab == 1) {
|
||||
GuiCustomScroll hooks = new GuiCustomScroll(this, 1);
|
||||
hooks.allowUserInput = false;
|
||||
hooks.setSize(108, 198);
|
||||
hooks.guiLeft = this.guiLeft - 110;
|
||||
hooks.guiTop = this.guiTop + 14;
|
||||
|
||||
hooks.setUnsortedList(this.hooklist);
|
||||
this.addScroll(hooks);
|
||||
GuiNpcLabel hookLabel = new GuiNpcLabel(0, "script.hooks", hooks.guiLeft, this.guiTop + 5);
|
||||
hookLabel.color = 11184810;
|
||||
this.addLabel(hookLabel);
|
||||
JaninoScript container = this.container;
|
||||
if (textArea == null)
|
||||
textArea = new GuiScriptTextArea(this, 2, this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
|
||||
else
|
||||
textArea.init(this.guiLeft + 1 + yoffset, this.guiTop + yoffset, this.xSize - 108 - yoffset, (int) ((double) this.ySize * 0.96) - yoffset * 2, container == null ? "" : container.script);
|
||||
textArea.enableCodeHighlighting();
|
||||
textArea.setListener(this);
|
||||
this.closeOnEsc(textArea::closeOnEsc);
|
||||
this.addTextField(textArea);
|
||||
|
||||
int left1 = this.guiLeft + this.xSize - 104;
|
||||
this.addButton(new GuiNpcButton(102, left1, this.guiTop + yoffset, 60, 20, "gui.clear"));
|
||||
this.addButton(new GuiNpcButton(101, left1 + 61, this.guiTop + yoffset, 60, 20, "gui.paste"));
|
||||
this.addButton(new GuiNpcButton(100, left1, this.guiTop + 21 + yoffset, 60, 20, "gui.copy"));
|
||||
this.addButton(new GuiNpcButton(105, left1 + 61, this.guiTop + 21 + yoffset, 60, 20, "gui.remove"));
|
||||
|
||||
this.addButton(new GuiNpcButton(107, left1, this.guiTop + 66 + yoffset, 80, 20, "script.loadscript"));
|
||||
// this.getButton(107).enabled = false;
|
||||
|
||||
GuiCustomScroll scroll = (new GuiCustomScroll(this, 0)).setUnselectable();
|
||||
scroll.setSize(100, (int) ((double) this.ySize * 0.54) - yoffset * 2);
|
||||
scroll.guiLeft = left1;
|
||||
scroll.guiTop = this.guiTop + 88 + yoffset;
|
||||
if (container != null)
|
||||
scroll.setList(container.externalScripts);
|
||||
|
||||
this.addScroll(scroll);
|
||||
} else {
|
||||
GuiNpcTextArea var8 = new GuiNpcTextArea(2, this, this.guiLeft + 4 + yoffset, this.guiTop + 6 + yoffset, this.xSize - 160 - yoffset, (int) ((float) this.ySize * 0.92F) - yoffset * 2, this.getConsoleText());
|
||||
var8.enabled = false;
|
||||
this.addTextField(var8);
|
||||
int var9 = this.guiLeft + this.xSize - 150;
|
||||
this.addButton(new GuiNpcButton(100, var9, this.guiTop + 125, 60, 20, "gui.copy"));
|
||||
this.addButton(new GuiNpcButton(102, var9, this.guiTop + 146, 60, 20, "gui.clear"));
|
||||
this.addLabel(new GuiNpcLabel(1, "script.language", var9, this.guiTop + 15));
|
||||
String containerLang = container.getLanguage();
|
||||
this.addButton(new GuiNpcButton(103, var9 + 60, this.guiTop + 10, 80, 20, new String[]{containerLang.equals("Java") ? "Janino (JVM 8)" : containerLang},
|
||||
this.getLanguageIndex()));
|
||||
// this.getButton(103).enabled = !this.languages.isEmpty();
|
||||
this.addLabel(new GuiNpcLabel(2, "gui.enabled", var9, this.guiTop + 36));
|
||||
// Note: GuiJaninoScript is deprecated; enabled button disabled
|
||||
this.addButton(new GuiNpcButton(104, var9 + 60, this.guiTop + 31, 50, 20, new String[]{"gui.no", "gui.yes"}, 0));
|
||||
|
||||
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
|
||||
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
|
||||
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
|
||||
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
|
||||
}
|
||||
|
||||
this.xSize = 420;
|
||||
this.ySize = 256;
|
||||
}
|
||||
|
||||
public void customScrollClicked(int i, int j, int k, GuiCustomScroll scroll) {
|
||||
String hook = scroll.getSelected();
|
||||
if (this.previousHookClicked.equals(hook)) {
|
||||
String addString = "";
|
||||
if (!this.getTextField(2)
|
||||
.getText()
|
||||
.isEmpty()) {
|
||||
addString = addString + "\n";
|
||||
}
|
||||
|
||||
addString = addString + generateMethodStub(hookMap.get(hook));
|
||||
this.getTextField(2)
|
||||
.setText(this.getTextField(2)
|
||||
.getText() + addString);
|
||||
this.previousHookClicked = "";
|
||||
} else {
|
||||
this.previousHookClicked = hook;
|
||||
}
|
||||
}
|
||||
|
||||
public void confirmClicked(boolean flag, int i) {
|
||||
if (flag) {
|
||||
if (i == 0)
|
||||
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
|
||||
else if (i == 1)
|
||||
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
|
||||
else if (i == 2)
|
||||
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
|
||||
else if (i == 3)
|
||||
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
|
||||
|
||||
if (i == 10) { //Remove
|
||||
this.container.setScript("");
|
||||
this.activeTab = 0;
|
||||
} else if (i == 101) { //Paste
|
||||
this.getTextField(2)
|
||||
.setText(NoppesStringUtils.getClipboardContents());
|
||||
this.setScript();
|
||||
} else if (i == 102) { //Clear
|
||||
if (this.activeTab == 1)
|
||||
container.script = "";
|
||||
else
|
||||
this.container.clearConsole();
|
||||
|
||||
this.initGui();
|
||||
}
|
||||
}
|
||||
|
||||
this.displayGuiScreen(this);
|
||||
}
|
||||
|
||||
protected void actionPerformed(GuiButton guibutton) {
|
||||
if (guibutton.id == -1) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (guibutton.id == 0) {
|
||||
this.setScript();
|
||||
this.activeTab = 0;
|
||||
this.initGui();
|
||||
container.ensureCompiled();
|
||||
}
|
||||
|
||||
if (guibutton.id == this.scriptLimit) {
|
||||
// if (container.container == null)
|
||||
//this.container.container = new ScriptContainer(this.container);
|
||||
// else
|
||||
// this.setScript();
|
||||
this.activeTab = 1;
|
||||
this.initGui();
|
||||
}
|
||||
|
||||
if (guibutton.id == 109) {
|
||||
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://kamkeel.github.io/CustomNPC-Plus/", 0, true));
|
||||
} else if (guibutton.id == 110) {
|
||||
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
|
||||
} else if (guibutton.id == 111) {
|
||||
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
|
||||
} else if (guibutton.id == 112) {
|
||||
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
|
||||
}
|
||||
|
||||
GuiYesNo confirmScreen;
|
||||
|
||||
//Copy
|
||||
if (guibutton.id == 100) {
|
||||
NoppesStringUtils.setClipboardContents(this.getTextField(2)
|
||||
.getText());
|
||||
}
|
||||
//Paste
|
||||
else if (guibutton.id == 101) {
|
||||
GuiYesNo guiyesno = new GuiYesNo(this, StatCollector.translateToLocal("gui.paste"), StatCollector.translateToLocal("gui.sure"), 101);
|
||||
this.displayGuiScreen(guiyesno);
|
||||
}
|
||||
//Clear
|
||||
else if (guibutton.id == 102) {
|
||||
confirmScreen = new GuiYesNo(this, StatCollector.translateToLocal("gui.clear"), StatCollector.translateToLocal("gui.sure"), 102);
|
||||
this.displayGuiScreen(confirmScreen);
|
||||
}
|
||||
//Enable
|
||||
else if (guibutton.id == 104) {
|
||||
// Deprecated GUI - enabled is now per-handler, not per-unit
|
||||
}
|
||||
//Remove
|
||||
else if (guibutton.id == 105) {
|
||||
confirmScreen = new GuiYesNo(this, "", guibutton.displayString, 10);
|
||||
this.displayGuiScreen(confirmScreen);
|
||||
}
|
||||
//Load Script
|
||||
else if (guibutton.id == 107) {
|
||||
setSubGui(new SubGuiSelectList(allExternalScripts, container.externalScripts, "All Scripts", "Selected Scripts"));
|
||||
}
|
||||
}
|
||||
|
||||
public void subGuiClosed(SubGuiInterface sub) {
|
||||
if (sub instanceof SubGuiSelectList)
|
||||
container.setExternalScripts(((SubGuiSelectList) sub).selected);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a stub string for a given Method.
|
||||
*/
|
||||
public static String generateMethodStub(Method method) {
|
||||
String mods = java.lang.reflect.Modifier.toString(method.getModifiers());
|
||||
if (!mods.isEmpty())
|
||||
mods += " ";
|
||||
|
||||
String returnTypeStr = method.getReturnType()
|
||||
.getSimpleName();
|
||||
String name = method.getName();
|
||||
|
||||
Map<String, Integer> typeCount = new HashMap<>();
|
||||
String params = Arrays.stream(method.getParameters())
|
||||
.map(p -> {
|
||||
String typeName = p.getType()
|
||||
.getSimpleName();
|
||||
String baseName = Character.toLowerCase(typeName.charAt(0)) + typeName.substring(1);
|
||||
|
||||
int count = typeCount.getOrDefault(baseName, 0) + 1;
|
||||
typeCount.put(baseName, count);
|
||||
|
||||
// append number if same type of arg exists
|
||||
String paramName = count == 1 ? baseName : baseName + (count - 1);
|
||||
|
||||
return typeName + " " + paramName;
|
||||
})
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
String body;
|
||||
Class<?> returnType = method.getReturnType();
|
||||
if (returnType == void.class)
|
||||
body = "";
|
||||
else if (returnType.isPrimitive()) {
|
||||
if (returnType == boolean.class)
|
||||
body = " return false;";
|
||||
else if (returnType == char.class)
|
||||
body = " return '\\0';";
|
||||
else
|
||||
body = " return 0;";
|
||||
} else {
|
||||
body = " return null;";
|
||||
}
|
||||
|
||||
return String.format("%s%s %s(%s) {\n%s\n}\n", mods, returnTypeStr, name, params, body);
|
||||
}
|
||||
|
||||
private String getConsoleText() {
|
||||
Map<Long, String> map = this.container.getConsole();
|
||||
StringBuilder builder = new StringBuilder();
|
||||
Iterator var3 = map.entrySet()
|
||||
.iterator();
|
||||
|
||||
while (var3.hasNext()) {
|
||||
Map.Entry<Long, String> entry = (Map.Entry) var3.next();
|
||||
builder.insert(0, new Date(entry.getKey()) + entry.getValue() + "\n");
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private int getLanguageIndex() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
private void setScript() {
|
||||
if (this.activeTab == 1) {
|
||||
String text = this.getTextField(2)
|
||||
.getText();
|
||||
text = text.replace("\r\n", "\n");
|
||||
text = text.replace("\r", "\n");
|
||||
container.setScript(text);
|
||||
}
|
||||
}
|
||||
|
||||
public void save() {
|
||||
if (saveFunction != null)
|
||||
saveFunction.run();
|
||||
else if (parent instanceof GuiNPCInterface)
|
||||
((GuiNPCInterface) parent).save();
|
||||
}
|
||||
|
||||
public void textUpdate(String text) {
|
||||
// container.setScript(text);
|
||||
}
|
||||
|
||||
public static GuiJaninoScript create(GuiScreen parent, JaninoScript script, int width, int height) {
|
||||
GuiJaninoScript gui = new GuiJaninoScript(parent, script);
|
||||
gui.setWorldAndResolution(Minecraft.getMinecraft(), width, height);
|
||||
Minecraft.getMinecraft().currentScreen = gui;
|
||||
gui.initGui();
|
||||
return gui;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
this.save();
|
||||
this.setScript();
|
||||
container.ensureCompiled();
|
||||
parent.setWorldAndResolution(mc, width, height);
|
||||
parent.initGui();
|
||||
mc.currentScreen = parent;
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,10 @@ import net.minecraft.nbt.NBTTagList;
|
||||
import net.minecraft.util.StatCollector;
|
||||
import noppes.npcs.NoppesStringUtils;
|
||||
import noppes.npcs.client.NoppesUtil;
|
||||
import noppes.npcs.controllers.APIRegistry;
|
||||
import noppes.npcs.client.gui.util.GuiCustomScroll;
|
||||
import noppes.npcs.client.gui.util.SubGuiAPISelect;
|
||||
import noppes.npcs.client.gui.util.SubGuiConfirmLink;
|
||||
import noppes.npcs.client.gui.util.GuiMenuTopButton;
|
||||
import noppes.npcs.client.gui.util.GuiNPCInterface;
|
||||
import noppes.npcs.client.gui.util.GuiNpcButton;
|
||||
@@ -127,6 +130,8 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
// Request data from server
|
||||
if (handler instanceof IScriptHandlerPacket)
|
||||
((IScriptHandlerPacket) handler).requestData();
|
||||
else
|
||||
gui.serverDataReceived = true; // No server data to wait for
|
||||
|
||||
return gui;
|
||||
}
|
||||
@@ -366,13 +371,11 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
}
|
||||
|
||||
this.addButton(new GuiNpcButton(109, var9, this.guiTop + 78, 80, 20, "gui.website"));
|
||||
this.addButton(new GuiNpcButton(112, var9 + 81, this.guiTop + 78, 80, 20, "gui.forum"));
|
||||
this.addButton(new GuiNpcButton(110, var9, this.guiTop + 99, 80, 20, "script.apidoc"));
|
||||
this.addButton(new GuiNpcButton(111, var9 + 81, this.guiTop + 99, 80, 20, "script.apisrc"));
|
||||
this.addButton(new GuiNpcButton(110, var9 + 81, this.guiTop + 78, 80, 20, "gui.api"));
|
||||
|
||||
// Disable all buttons until server data arrives
|
||||
if (!serverDataReceived) {
|
||||
for (int btnId : new int[]{100, 102, 103, 104, 106, 109, 110, 111, 112}) {
|
||||
for (int btnId : new int[]{100, 102, 103, 104, 106, 109, 110}) {
|
||||
GuiNpcButton btn = getButton(btnId);
|
||||
if (btn != null) btn.enabled = false;
|
||||
}
|
||||
@@ -568,19 +571,35 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
*/
|
||||
protected List<String> getLanguageOptions() {
|
||||
List<String> options = new ArrayList<>();
|
||||
|
||||
// Start with languages known from the server
|
||||
if (this.languages != null && !this.languages.isEmpty())
|
||||
options.addAll(this.languages.keySet());
|
||||
|
||||
if ((options.isEmpty() || !options.contains("Java")) && this.handler != null && this.handler.supportsJanino()) {
|
||||
List<String> scripts = new ArrayList<>();
|
||||
if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) {
|
||||
scripts.addAll(ScriptController.Instance.scripts.keySet());
|
||||
if (this.handler != null) {
|
||||
if (this.handler.supportsJanino()) {
|
||||
// Handler supports Java — ensure it's in the list
|
||||
if (!options.contains("Java")) {
|
||||
List<String> scripts = new ArrayList<>();
|
||||
if (ScriptController.Instance != null && ScriptController.Instance.scripts != null) {
|
||||
scripts.addAll(ScriptController.Instance.scripts.keySet());
|
||||
}
|
||||
if (this.languages == null)
|
||||
this.languages = new HashMap();
|
||||
if (!this.languages.containsKey("Java"))
|
||||
this.languages.put("Java", scripts);
|
||||
options.add("Java");
|
||||
}
|
||||
} else {
|
||||
// Handler does not support Java — remove it
|
||||
options.remove("Java");
|
||||
}
|
||||
|
||||
// Ensure at least the handler's default language is present
|
||||
String defaultLang = this.handler.getLanguage();
|
||||
if (defaultLang != null && !defaultLang.isEmpty() && !options.contains(defaultLang)) {
|
||||
options.add(0, defaultLang);
|
||||
}
|
||||
if (this.languages == null)
|
||||
this.languages = new HashMap();
|
||||
if (!this.languages.containsKey("Java"))
|
||||
this.languages.put("Java", scripts);
|
||||
options.add("Java");
|
||||
}
|
||||
|
||||
return options;
|
||||
@@ -592,17 +611,6 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
this.openLink("https://www.curseforge.com/minecraft/mc-mods/customnpc-plus");
|
||||
}
|
||||
|
||||
if (i == 1) {
|
||||
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
|
||||
}
|
||||
|
||||
if (i == 2) {
|
||||
this.openLink("https://kamkeel.github.io/CustomNPC-Plus/");
|
||||
}
|
||||
|
||||
if (i == 3) {
|
||||
this.openLink("http://www.minecraftforge.net/forum/index.php/board,122.0.html");
|
||||
}
|
||||
if (i == 10) {
|
||||
handler.removeScriptUnit(this.activeTab - 1);
|
||||
this.activeTab = 0;
|
||||
@@ -698,15 +706,12 @@ public class GuiScriptInterface extends GuiNPCInterface implements GuiYesNoCallb
|
||||
}
|
||||
|
||||
if (guibutton.id == 110) {
|
||||
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/KAMKEEL/CustomNPC-Plus-API", 1, true));
|
||||
}
|
||||
|
||||
if (guibutton.id == 111) {
|
||||
this.displayGuiScreen(new GuiConfirmOpenLink(this, "https://github.com/Noppes/CustomNPCsAPI", 2, true));
|
||||
}
|
||||
|
||||
if (guibutton.id == 112) {
|
||||
this.displayGuiScreen(new GuiConfirmOpenLink(this, "http://www.minecraftforge.net/forum/index.php/board,122.0.html", 3, true));
|
||||
if (APIRegistry.Instance.size() == 1) {
|
||||
String url = APIRegistry.Instance.getEntries().values().iterator().next();
|
||||
this.setSubGui(new SubGuiConfirmLink(url));
|
||||
} else {
|
||||
this.setSubGui(new SubGuiAPISelect());
|
||||
}
|
||||
}
|
||||
|
||||
if (guibutton.id == 100) {
|
||||
|
||||
@@ -2050,17 +2050,9 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
String childIndent = indent + " ";
|
||||
String after = getSelectionAfterText();
|
||||
|
||||
// If the next non-whitespace char is '}', don't insert another closer.
|
||||
int nextNonWs = 0;
|
||||
while (nextNonWs < after.length() && Character.isWhitespace(after.charAt(nextNonWs))) {
|
||||
nextNonWs++;
|
||||
}
|
||||
if (nextNonWs < after.length() && after.charAt(nextNonWs) == '}') {
|
||||
addText("\n" + childIndent);
|
||||
scrollToCursor();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if there's non-whitespace content on the current line after the cursor.
|
||||
// If so, just add a newline + child indent without inserting a closing brace
|
||||
// (the user is typing inside an existing expression).
|
||||
int firstNewline = after.indexOf('\n');
|
||||
String leadingSegment = firstNewline == -1 ? after : after.substring(0, firstNewline);
|
||||
if (leadingSegment.trim().length() > 0) {
|
||||
@@ -2069,7 +2061,14 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean hasMatchingCloseSameIndent = false;
|
||||
// Use BracketMatcher to determine if the opening '{' already has a
|
||||
// properly matched closing '}' at the correct indent. Pure indent-based
|
||||
// heuristics (scanning the 'after' substring) are unreliable for lambdas
|
||||
// and nested callbacks; BracketMatcher uses stack-based pairing on the
|
||||
// full text, then we verify the close brace sits at the same indent as
|
||||
// the open brace's line — ensuring parent-scoped braces aren't mistaken
|
||||
// for our own.
|
||||
boolean hasMatchingClose = false;
|
||||
try {
|
||||
int openLineIdx = -1;
|
||||
int bracePos = prevNonWs;
|
||||
@@ -2084,24 +2083,42 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
if (openLineIdx >= 0) {
|
||||
List<int[]> spans = BracketMatcher.computeBraceSpans(text, this.container.lines);
|
||||
for (int[] span : spans) {
|
||||
int spanOpen = span[1];
|
||||
int spanClose = span[2];
|
||||
if (spanOpen == openLineIdx) {
|
||||
int closeIndent = IndentHelper.getLineIndent(this.container.lines.get(spanClose).text);
|
||||
if (closeIndent == indent.length()) {
|
||||
hasMatchingCloseSameIndent = true;
|
||||
if (span[1] == openLineIdx) {
|
||||
int closeLineIdx = span[2];
|
||||
if (closeLineIdx < this.container.lines.size()) {
|
||||
int closeIndent = IndentHelper.getLineIndent(
|
||||
this.container.lines.get(closeLineIdx).text);
|
||||
// <= handles multi-line declarations where '{' sits on a
|
||||
// continuation line with higher indent than the closing '}'
|
||||
if (closeIndent <= indent.length()) {
|
||||
hasMatchingClose = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
hasMatchingCloseSameIndent = false;
|
||||
hasMatchingClose = false;
|
||||
}
|
||||
|
||||
if (hasMatchingCloseSameIndent) {
|
||||
if (hasMatchingClose) {
|
||||
addText("\n" + childIndent);
|
||||
scrollToCursor();
|
||||
} else if (isLambdaOpening(prevNonWs, text)) {
|
||||
int parenPos = findLambdaParentParen(prevNonWs, text);
|
||||
if (parenPos >= 0) {
|
||||
String parentIndent = getParentIndentForLambda(parenPos, container.lines);
|
||||
String insert = "\n" + childIndent + "\n" + parentIndent + "});";
|
||||
setText(before + insert + after);
|
||||
selection.reset(before.length() + 1 + childIndent.length());
|
||||
scrollToCursor();
|
||||
} else {
|
||||
String insert = "\n" + childIndent + "\n" + indent + "}";
|
||||
setText(before + insert + after);
|
||||
selection.reset(before.length() + 1 + childIndent.length());
|
||||
scrollToCursor();
|
||||
}
|
||||
} else {
|
||||
String insert = "\n" + childIndent + "\n" + indent + "}";
|
||||
setText(before + insert + after);
|
||||
@@ -2302,15 +2319,17 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the current line is whitespace-only, delete the whole line
|
||||
// (including the trailing newline if present). This makes Backspace
|
||||
// intuitive on blank/indented lines outside any recognized scope.
|
||||
// If the current line is whitespace-only, remove it by deleting the
|
||||
// preceding newline and the line's content, but preserve any trailing
|
||||
// newline so the following line (e.g. a closing brace) stays in place.
|
||||
LineData currCheck = selection.findCurrentLine(container.lines);
|
||||
if (currCheck != null && currCheck.text.trim().length() == 0) {
|
||||
String before = text.substring(0, ValueUtil.clamp(currCheck.start - 1, 0, text.length()));
|
||||
String after = text.substring(Math.min(currCheck.end, text.length()));
|
||||
setText(before + after, true); // Use atomic undo
|
||||
int newCursor = Math.max(0, currCheck.start - 1);
|
||||
int removeStart = ValueUtil.clamp(currCheck.start - 1, 0, text.length());
|
||||
int contentEnd = Math.min(currCheck.start + currCheck.text.length(), text.length());
|
||||
String before = text.substring(0, removeStart);
|
||||
String after = text.substring(contentEnd);
|
||||
setText(before + after, true);
|
||||
int newCursor = Math.max(0, removeStart);
|
||||
selection.reset(newCursor);
|
||||
scrollToCursor();
|
||||
return true;
|
||||
@@ -2709,6 +2728,135 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
return text.substring(lineStart, p);
|
||||
}
|
||||
|
||||
private boolean isLambdaOpening(int bracePos, String fullText) {
|
||||
if (fullText == null || bracePos <= 1) {
|
||||
return false;
|
||||
}
|
||||
int scan = bracePos - 1;
|
||||
while (scan >= 0 && (fullText.charAt(scan) == ' ' || fullText.charAt(scan) == '\t')) {
|
||||
scan--;
|
||||
}
|
||||
if (scan < 1) {
|
||||
return false;
|
||||
}
|
||||
char c1 = fullText.charAt(scan - 1);
|
||||
char c2 = fullText.charAt(scan);
|
||||
return (c1 == '-' && c2 == '>') || (c1 == '=' && c2 == '>');
|
||||
}
|
||||
|
||||
// Reverse-scans from bracePos to find the unmatched '(' that this lambda is an
|
||||
// argument of. Properly handles nested parens/braces, strings, and comments.
|
||||
// Returns the position of the enclosing '(' or -1 if not found.
|
||||
private int findLambdaParentParen(int bracePos, String fullText) {
|
||||
if (fullText == null || bracePos <= 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int parenDepth = 0;
|
||||
int braceDepth = 0;
|
||||
boolean inString = false;
|
||||
boolean inBlockComment = false;
|
||||
char stringDelim = 0;
|
||||
|
||||
for (int i = bracePos - 1; i >= 0; i--) {
|
||||
char c = fullText.charAt(i);
|
||||
char prev = i > 0 ? fullText.charAt(i - 1) : 0;
|
||||
|
||||
// Reverse block-comment: entered at '*/', exits at '/*'
|
||||
if (inBlockComment) {
|
||||
if (c == '*' && prev == '/') {
|
||||
inBlockComment = false;
|
||||
i--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '/' && prev == '*') {
|
||||
inBlockComment = true;
|
||||
i--;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inString) {
|
||||
if (c == stringDelim) {
|
||||
int bs = 0;
|
||||
for (int j = i - 1; j >= 0 && fullText.charAt(j) == '\\'; j--) {
|
||||
bs++;
|
||||
}
|
||||
if (bs % 2 == 0) {
|
||||
inString = false;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '"' || c == '\'' || c == '`') {
|
||||
inString = true;
|
||||
stringDelim = c;
|
||||
continue;
|
||||
}
|
||||
|
||||
// For line comments: when scanning backwards and hitting a newline,
|
||||
// check if the preceding line contains a // comment. If so, skip
|
||||
// backwards past it to avoid counting brackets inside comments.
|
||||
if (c == '\n') {
|
||||
int lineStart = fullText.lastIndexOf('\n', i - 1) + 1;
|
||||
int commentIdx = findLineCommentStart(fullText, lineStart, i);
|
||||
if (commentIdx >= 0) {
|
||||
i = commentIdx;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '}') {
|
||||
braceDepth++;
|
||||
} else if (c == '{') {
|
||||
if (braceDepth > 0) {
|
||||
braceDepth--;
|
||||
}
|
||||
if (braceDepth == 0) {
|
||||
return -1;
|
||||
}
|
||||
} else if (c == ')') {
|
||||
parenDepth++;
|
||||
} else if (c == '(') {
|
||||
if (parenDepth > 0) {
|
||||
parenDepth--;
|
||||
} else {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private int findLineCommentStart(String text, int lineStart, int lineEnd) {
|
||||
boolean inStr = false;
|
||||
char strDelim = 0;
|
||||
for (int i = lineStart; i < lineEnd; i++) {
|
||||
char c = text.charAt(i);
|
||||
if (inStr) {
|
||||
if (c == strDelim && (i == 0 || text.charAt(i - 1) != '\\')) {
|
||||
inStr = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"' || c == '\'' || c == '`') {
|
||||
inStr = true;
|
||||
strDelim = c;
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && i + 1 < lineEnd && text.charAt(i + 1) == '/') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private String getParentIndentForLambda(int parenPos, List<LineData> lines) {
|
||||
return getLogicalLineIndentAt(parenPos);
|
||||
}
|
||||
|
||||
private boolean isShiftKeyDown() {
|
||||
return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54);
|
||||
}
|
||||
@@ -2794,9 +2942,11 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
}
|
||||
|
||||
private void formatText() {
|
||||
// Calculate viewport width for line wrapping (account for gutter and scrollbar)
|
||||
int viewportWidth = this.width - LINE_NUMBER_GUTTER_WIDTH - 10;
|
||||
IndentHelper.FormatResult result = IndentHelper.formatText(text, selection.getCursorPosition(), viewportWidth);
|
||||
int viewportPixels = this.width - LINE_NUMBER_GUTTER_WIDTH - 10;
|
||||
int avgCharWidth = Math.max(1, ClientProxy.Font.width("abcdefghijklmnopqrstuvwxyz") / 26);
|
||||
int viewportChars = (int) (viewportPixels * 0.8f / avgCharWidth);
|
||||
int maxLineLength = Math.max(60, Math.min(viewportChars, 120));
|
||||
IndentHelper.FormatResult result = IndentHelper.formatText(text, selection.getCursorPosition(), maxLineLength);
|
||||
setText(result.text);
|
||||
selection.reset(Math.max(0, Math.min(result.cursorPosition, this.text.length())));
|
||||
}
|
||||
@@ -2862,41 +3012,22 @@ public class GuiScriptTextArea extends GuiNpcTextField {
|
||||
return;
|
||||
int tab = getTabSize();
|
||||
int indentLen = IndentHelper.getLineIndent(currentLine.text);
|
||||
int textStartPos = currentLine.start + indentLen;
|
||||
|
||||
if (selection.getCursorPosition() <= textStartPos) {
|
||||
// Cursor before any text: reduce leading indent to previous tab stop
|
||||
int targetIndent = Math.max(0, ((indentLen - 1) / tab) * tab);
|
||||
String newIndent = repeatSpace(targetIndent);
|
||||
String rest = currentLine.text.substring(indentLen);
|
||||
String before = text.substring(0, currentLine.start);
|
||||
int contentEnd = Math.min(currentLine.start + currentLine.text.length(), text.length());
|
||||
int sepEnd = Math.min(currentLine.end, text.length());
|
||||
String sep = contentEnd < sepEnd ? text.substring(contentEnd, sepEnd) : "";
|
||||
String after = text.substring(sepEnd);
|
||||
setText(before + newIndent + rest + sep + after);
|
||||
int newCursor = currentLine.start + targetIndent;
|
||||
selection.reset(Math.min(newCursor, this.text.length()));
|
||||
} else {
|
||||
// Cursor after start of text: remove up to previous tab stop worth of spaces immediately before cursor
|
||||
int column = selection.getCursorPosition() - currentLine.start;
|
||||
int mod = column % tab;
|
||||
int toRemove = mod == 0 ? tab : mod;
|
||||
int removed = 0;
|
||||
int pos = selection.getCursorPosition() - 1;
|
||||
while (pos >= currentLine.start && removed < toRemove && text.charAt(pos) == ' ') {
|
||||
pos--;
|
||||
removed++;
|
||||
}
|
||||
if (removed > 0) {
|
||||
int removeStart = pos + 1;
|
||||
String before = text.substring(0, removeStart);
|
||||
String after = text.substring(selection.getCursorPosition());
|
||||
setText(before + after);
|
||||
int newCursor = removeStart;
|
||||
selection.reset(Math.min(newCursor, this.text.length()));
|
||||
}
|
||||
}
|
||||
if (indentLen == 0)
|
||||
return;
|
||||
|
||||
int targetIndent = Math.max(0, ((indentLen - 1) / tab) * tab);
|
||||
int removed = indentLen - targetIndent;
|
||||
String newIndent = repeatSpace(targetIndent);
|
||||
String rest = currentLine.text.substring(indentLen);
|
||||
String before = text.substring(0, currentLine.start);
|
||||
int contentEnd = Math.min(currentLine.start + currentLine.text.length(), text.length());
|
||||
int sepEnd = Math.min(currentLine.end, text.length());
|
||||
String sep = contentEnd < sepEnd ? text.substring(contentEnd, sepEnd) : "";
|
||||
String after = text.substring(sepEnd);
|
||||
setText(before + newIndent + rest + sep + after);
|
||||
int newCursor = Math.max(currentLine.start, selection.getCursorPosition() - removed);
|
||||
selection.reset(Math.min(newCursor, this.text.length()));
|
||||
}
|
||||
|
||||
// ==================== CURSOR MANAGEMENT ====================
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package noppes.npcs.client.gui.util;
|
||||
|
||||
import net.minecraft.client.gui.GuiButton;
|
||||
import noppes.npcs.controllers.APIRegistry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class SubGuiAPISelect extends SubGuiInterface implements ISubGuiListener {
|
||||
private final List<String> names;
|
||||
private final List<String> urls;
|
||||
|
||||
public SubGuiAPISelect() {
|
||||
LinkedHashMap<String, String> entries = APIRegistry.Instance.getEntries();
|
||||
this.names = new ArrayList<>(entries.keySet());
|
||||
this.urls = new ArrayList<>(entries.values());
|
||||
|
||||
this.xSize = 180;
|
||||
this.ySize = 40 + names.size() * 24;
|
||||
this.closeOnEsc = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initGui() {
|
||||
super.initGui();
|
||||
|
||||
addLabel(new GuiNpcLabel(0, "gui.api", guiLeft + 10, guiTop + 10, 0xFFFFFF));
|
||||
|
||||
for (int i = 0; i < names.size(); i++) {
|
||||
addButton(new GuiNpcButton(i, guiLeft + 10, guiTop + 28 + i * 24, 160, 20, names.get(i)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
|
||||
drawGradientRect(guiLeft, guiTop, guiLeft + xSize, guiTop + ySize, 0xC0101010, 0xC0101010);
|
||||
super.drawScreen(mouseX, mouseY, partialTicks);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void actionPerformed(GuiButton guibutton) {
|
||||
int id = guibutton.id;
|
||||
if (id >= 0 && id < urls.size()) {
|
||||
setSubGui(new SubGuiConfirmLink(urls.get(id)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subGuiClosed(SubGuiInterface subgui) {
|
||||
if (subgui instanceof SubGuiConfirmLink && ((SubGuiConfirmLink) subgui).confirmed) {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package noppes.npcs.client.gui.util;
|
||||
|
||||
import net.minecraft.client.gui.GuiButton;
|
||||
import net.minecraft.client.resources.I18n;
|
||||
import noppes.npcs.NoppesStringUtils;
|
||||
|
||||
public class SubGuiConfirmLink extends SubGuiInterface {
|
||||
private final String url;
|
||||
public boolean confirmed = false;
|
||||
|
||||
public SubGuiConfirmLink(String url) {
|
||||
this.url = url;
|
||||
this.xSize = 260;
|
||||
this.ySize = 120;
|
||||
this.closeOnEsc = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initGui() {
|
||||
super.initGui();
|
||||
|
||||
GuiNpcLabel titleLabel = new GuiNpcLabel(0, I18n.format("chat.link.confirmTrusted"), guiLeft, guiTop + 10, 0xFFFFFF);
|
||||
titleLabel.center(xSize);
|
||||
addLabel(titleLabel);
|
||||
|
||||
GuiNpcLabel urlLabel = new GuiNpcLabel(1, url, guiLeft, guiTop + 28, 0xCCCCFF);
|
||||
urlLabel.center(xSize);
|
||||
addLabel(urlLabel);
|
||||
|
||||
int btnWidth = 115;
|
||||
int spacing = 10;
|
||||
int totalWidth = btnWidth * 2 + spacing;
|
||||
int startX = guiLeft + (xSize - totalWidth) / 2;
|
||||
|
||||
addButton(new GuiNpcButton(0, startX, guiTop + 52, btnWidth, 20, "chat.link.open"));
|
||||
addButton(new GuiNpcButton(1, startX + btnWidth + spacing, guiTop + 52, btnWidth, 20, "chat.copy"));
|
||||
addButton(new GuiNpcButton(2, guiLeft + (xSize - btnWidth) / 2, guiTop + 78, btnWidth, 20, "gui.cancel"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
|
||||
drawGradientRect(0, 0, width, height, 0xC0101010, 0xC0101010);
|
||||
super.drawScreen(mouseX, mouseY, partialTicks);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void actionPerformed(GuiButton guibutton) {
|
||||
if (guibutton.id == 0) {
|
||||
confirmed = true;
|
||||
openLink(url);
|
||||
} else if (guibutton.id == 1) {
|
||||
confirmed = true;
|
||||
NoppesStringUtils.setClipboardContents(url);
|
||||
}
|
||||
close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save() {
|
||||
}
|
||||
}
|
||||
@@ -326,7 +326,8 @@ public class BracketMatcher {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a brace at given position has a matching close with same indent
|
||||
* Check if a brace at given position has a matching close with compatible indent.
|
||||
* Uses <= to handle multi-line declarations where '{' is on a continuation line.
|
||||
*/
|
||||
public static boolean hasMatchingCloseWithSameIndent(String text, int bracePos, List<LineData> lines, int currentIndent) {
|
||||
if (text == null || lines == null || bracePos < 0) return false;
|
||||
@@ -350,7 +351,7 @@ public class BracketMatcher {
|
||||
if (closeLineIdx < lines.size()) {
|
||||
String closeLine = lines.get(closeLineIdx).text;
|
||||
int closeIndent = getLineIndent(closeLine);
|
||||
return closeIndent == currentIndent;
|
||||
return closeIndent <= currentIndent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,17 +254,26 @@ public class FormatHelper {
|
||||
public String format(String text) {
|
||||
if (text == null || text.isEmpty()) return text;
|
||||
|
||||
// Process line by line to preserve structure
|
||||
String[] lines = text.split("\n", -1);
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
List<String> lambdaIndentStack = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
String line = formatLine(lines[i]);
|
||||
String line = lines[i];
|
||||
|
||||
if (!lambdaIndentStack.isEmpty()) {
|
||||
line = fixLambdaBlockIndent(line, lambdaIndentStack);
|
||||
}
|
||||
|
||||
line = formatLine(line);
|
||||
|
||||
if (settings.trimTrailingWhitespace) {
|
||||
line = trimTrailing(line);
|
||||
}
|
||||
|
||||
updateLambdaBlockStack(line, lambdaIndentStack);
|
||||
|
||||
result.append(line);
|
||||
if (i < lines.length - 1) {
|
||||
result.append("\n");
|
||||
@@ -274,6 +283,124 @@ public class FormatHelper {
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan a formatted line for arrow-block patterns ({@code -> {} or {@code => {})
|
||||
* and track open/close braces to maintain a stack of lambda block indent levels.
|
||||
* <p>
|
||||
* When an arrow-block opens, the line's leading indent is pushed onto the stack.
|
||||
* When a closing brace {@code }} is found and the stack is non-empty, the top
|
||||
* entry is popped (the brace closes the innermost lambda block).
|
||||
*/
|
||||
private void updateLambdaBlockStack(String line, List<String> stack) {
|
||||
String trimmed = line.trim();
|
||||
if (trimmed.isEmpty()) return;
|
||||
|
||||
String indent = extractIndent(line);
|
||||
String contentNoStrings = stripStringLiterals(trimmed);
|
||||
|
||||
int opens = 0;
|
||||
int closes = 0;
|
||||
for (int i = 0; i < contentNoStrings.length(); i++) {
|
||||
char c = contentNoStrings.charAt(i);
|
||||
if (c == '{') opens++;
|
||||
else if (c == '}') closes++;
|
||||
}
|
||||
|
||||
boolean hasArrowBlock = endsWithArrowBlock(contentNoStrings);
|
||||
|
||||
// Process closes first (a line like "});" closes the current block)
|
||||
int netCloses = closes - opens;
|
||||
if (netCloses > 0) {
|
||||
for (int j = 0; j < netCloses && !stack.isEmpty(); j++) {
|
||||
stack.remove(stack.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (hasArrowBlock) {
|
||||
stack.add(indent);
|
||||
} else if (opens > closes) {
|
||||
// Non-arrow block opened — only push if inside a lambda context already
|
||||
// to track nested depth correctly
|
||||
int netOpens = opens - closes;
|
||||
if (!stack.isEmpty()) {
|
||||
for (int j = 0; j < netOpens; j++) {
|
||||
stack.add(indent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix indentation for a line that's inside a lambda block body.
|
||||
* Body lines get parent indent + 4 spaces; closing braces get parent indent.
|
||||
*/
|
||||
private String fixLambdaBlockIndent(String line, List<String> stack) {
|
||||
if (stack.isEmpty()) return line;
|
||||
|
||||
String trimmed = line.trim();
|
||||
if (trimmed.isEmpty()) return line;
|
||||
|
||||
String currentIndent = extractIndent(line);
|
||||
String parentIndent = stack.get(stack.size() - 1);
|
||||
String bodyIndent = parentIndent + " ";
|
||||
|
||||
boolean isClosingBrace = trimmed.startsWith("}");
|
||||
|
||||
String requiredIndent = isClosingBrace ? parentIndent : bodyIndent;
|
||||
|
||||
if (getVisualLength(currentIndent) < getVisualLength(requiredIndent)) {
|
||||
return requiredIndent + trimmed;
|
||||
}
|
||||
|
||||
return line;
|
||||
}
|
||||
|
||||
private boolean endsWithArrowBlock(String contentNoStrings) {
|
||||
int lastOpenBrace = contentNoStrings.lastIndexOf('{');
|
||||
if (lastOpenBrace < 0) return false;
|
||||
|
||||
int matchingClose = contentNoStrings.indexOf('}', lastOpenBrace);
|
||||
if (matchingClose >= 0) return false;
|
||||
|
||||
int searchEnd = lastOpenBrace;
|
||||
while (searchEnd > 0 && contentNoStrings.charAt(searchEnd - 1) == ' ') searchEnd--;
|
||||
|
||||
if (searchEnd >= 2) {
|
||||
String beforeBrace = contentNoStrings.substring(searchEnd - 2, searchEnd);
|
||||
return beforeBrace.equals("->") || beforeBrace.equals("=>");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private String stripStringLiterals(String content) {
|
||||
StringBuilder sb = new StringBuilder(content.length());
|
||||
boolean inString = false;
|
||||
char stringChar = 0;
|
||||
|
||||
for (int i = 0; i < content.length(); i++) {
|
||||
char c = content.charAt(i);
|
||||
if (!inString) {
|
||||
if (c == '"' || c == '\'') {
|
||||
inString = true;
|
||||
stringChar = c;
|
||||
sb.append(' ');
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
} else {
|
||||
sb.append(' ');
|
||||
if (c == '\\' && i + 1 < content.length()) {
|
||||
i++;
|
||||
sb.append(' ');
|
||||
} else if (c == stringChar) {
|
||||
inString = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Split multiple statements on one line into separate lines with proper indentation.
|
||||
* E.g., " this.a = 1; this.b = 2;" becomes two lines
|
||||
@@ -1515,7 +1642,10 @@ public class FormatHelper {
|
||||
if (text == null || text.isEmpty()) return text;
|
||||
|
||||
int width = maxWidth > 0 ? maxWidth : settings.maxLineLength;
|
||||
String[] lines = text.split("\n", -1);
|
||||
|
||||
String joined = format(joinContinuationLines(text));
|
||||
|
||||
String[] lines = joined.split("\n", -1);
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
@@ -1543,6 +1673,92 @@ public class FormatHelper {
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Join continuation lines back onto their parent line so they can be
|
||||
* re-evaluated and re-wrapped at the current target width.
|
||||
* <p>
|
||||
* A "continuation line" is one whose trimmed content starts with an operator,
|
||||
* dot, comma, {@code ?}, or {@code :} — i.e. the wrapping markers used by
|
||||
* {@link #wrapCodeContent}. Only code continuation lines are joined; comment
|
||||
* lines ({@code //}, {@code *}) and lines inside lambda/block bodies (deeper
|
||||
* indent than expected) are left alone.
|
||||
*/
|
||||
private String joinContinuationLines(String text) {
|
||||
String[] lines = text.split("\n", -1);
|
||||
List<String> out = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
String line = lines[i];
|
||||
String trimmed = line.trim();
|
||||
|
||||
if (trimmed.isEmpty()
|
||||
|| trimmed.startsWith("//")
|
||||
|| trimmed.startsWith("/*")
|
||||
|| trimmed.startsWith("*")) {
|
||||
out.add(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean shouldJoin = false;
|
||||
int parentIdx = -1;
|
||||
|
||||
if ((isContinuationLine(trimmed) || startsWithDeclarationKeyword(trimmed))
|
||||
&& !out.isEmpty()) {
|
||||
int idx = out.size() - 1;
|
||||
while (idx >= 0 && out.get(idx).trim().isEmpty()) idx--;
|
||||
if (idx >= 0) {
|
||||
String parentTrimmed = out.get(idx).trim();
|
||||
char last = parentTrimmed.isEmpty() ? 0 : parentTrimmed.charAt(parentTrimmed.length() - 1);
|
||||
if (last != '{' && last != '}' && last != ';') {
|
||||
shouldJoin = true;
|
||||
parentIdx = idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldJoin && !out.isEmpty()) {
|
||||
int idx = out.size() - 1;
|
||||
while (idx >= 0 && out.get(idx).trim().isEmpty()) idx--;
|
||||
if (idx >= 0) {
|
||||
String parentTrimmed = out.get(idx).trim();
|
||||
if (!parentTrimmed.isEmpty()) {
|
||||
char last = parentTrimmed.charAt(parentTrimmed.length() - 1);
|
||||
if (last == '&' || last == '|' || last == '<' || last == '+'
|
||||
|| last == '-' || last == '?' || last == ',' || last == '>') {
|
||||
shouldJoin = true;
|
||||
parentIdx = idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldJoin) {
|
||||
out.set(parentIdx, trimTrailing(out.get(parentIdx)) + " " + trimmed);
|
||||
continue;
|
||||
}
|
||||
|
||||
out.add(line);
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < out.size(); i++) {
|
||||
sb.append(out.get(i));
|
||||
if (i < out.size() - 1) sb.append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private boolean startsWithDeclarationKeyword(String trimmed) {
|
||||
for (String kw : DECLARATION_BREAK_KEYWORDS) {
|
||||
if (trimmed.startsWith(kw)
|
||||
&& (trimmed.length() == kw.length()
|
||||
|| !Character.isJavaIdentifierPart(trimmed.charAt(kw.length())))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get visual length of a line (tabs count as 4 spaces).
|
||||
*/
|
||||
@@ -1860,6 +2076,13 @@ public class FormatHelper {
|
||||
* Core code wrapping logic (extracted from old wrapCodeLine, operates on code without comments).
|
||||
*/
|
||||
private String wrapCodeContent(String content, String indent, int maxWidth) {
|
||||
if (settings.wrapMethodArguments) {
|
||||
String argWrapped = tryArgumentAwareWrap(content, indent, maxWidth);
|
||||
if (argWrapped != null) {
|
||||
return argWrapped;
|
||||
}
|
||||
}
|
||||
|
||||
String wrapIndent = indent + spaces(settings.wrapIndentSpaces);
|
||||
String fullLine = indent + content;
|
||||
|
||||
@@ -1878,36 +2101,28 @@ public class FormatHelper {
|
||||
|
||||
int currentLen = getVisualLength(indent);
|
||||
int lastBreak = 0;
|
||||
boolean isFirstLine = true;
|
||||
|
||||
for (BreakPoint bp : breakPoints) {
|
||||
int segmentEnd = bp.position;
|
||||
String segment = content.substring(lastBreak, segmentEnd);
|
||||
int segmentLen = getVisualLength(segment);
|
||||
|
||||
if (currentLen + segmentLen > maxWidth && !isFirstLine) {
|
||||
if (currentLen + segmentLen > maxWidth && lastBreak > 0) {
|
||||
result.append("\n").append(wrapIndent);
|
||||
currentLen = getVisualLength(wrapIndent);
|
||||
isFirstLine = false;
|
||||
|
||||
segment = trimLeading(segment);
|
||||
} else if (currentLen + segmentLen > maxWidth && isFirstLine && lastBreak > 0) {
|
||||
result.append("\n").append(wrapIndent);
|
||||
currentLen = getVisualLength(wrapIndent);
|
||||
isFirstLine = false;
|
||||
}
|
||||
|
||||
result.append(segment);
|
||||
currentLen += getVisualLength(segment);
|
||||
lastBreak = segmentEnd;
|
||||
isFirstLine = false;
|
||||
}
|
||||
|
||||
if (lastBreak < content.length()) {
|
||||
String remaining = content.substring(lastBreak);
|
||||
int remLen = getVisualLength(remaining);
|
||||
|
||||
if (currentLen + remLen > maxWidth && !isFirstLine) {
|
||||
if (currentLen + remLen > maxWidth && lastBreak > 0) {
|
||||
result.append("\n").append(wrapIndent);
|
||||
remaining = trimLeading(remaining);
|
||||
}
|
||||
@@ -1919,8 +2134,188 @@ public class FormatHelper {
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim leading whitespace (Java 8 compatible).
|
||||
* Try argument-aware wrapping for method/constructor calls.
|
||||
* When a call like {@code new Foo(arg1, arg2, arg3)} exceeds maxWidth,
|
||||
* break after the opening paren, put each argument on its own line,
|
||||
* and close paren on its own line:
|
||||
* <pre>
|
||||
* new Foo(
|
||||
* arg1,
|
||||
* arg2,
|
||||
* arg3
|
||||
* )
|
||||
* </pre>
|
||||
*
|
||||
* @return the wrapped string, or {@code null} if this content doesn't
|
||||
* qualify for argument-aware wrapping
|
||||
*/
|
||||
private String tryArgumentAwareWrap(String content, String indent, int maxWidth) {
|
||||
String fullLine = indent + content;
|
||||
if (getVisualLength(fullLine) <= maxWidth) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int callParenIdx = findOutermostCallParen(content);
|
||||
if (callParenIdx < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int matchingClose = findMatchingClose(content, callParenIdx);
|
||||
if (matchingClose < 0 || matchingClose >= content.length()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String prefix = content.substring(0, callParenIdx + 1);
|
||||
String argsBody = content.substring(callParenIdx + 1, matchingClose);
|
||||
String suffix = content.substring(matchingClose);
|
||||
|
||||
List<String> args = splitArguments(argsBody);
|
||||
if (args.size() < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String argIndent = indent + spaces(settings.wrapIndentSpaces);
|
||||
String closeIndent = indent;
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.append(indent).append(prefix).append("\n");
|
||||
|
||||
for (int i = 0; i < args.size(); i++) {
|
||||
String arg = args.get(i).trim();
|
||||
if (arg.isEmpty()) continue;
|
||||
|
||||
result.append(argIndent).append(arg);
|
||||
if (i < args.size() - 1) {
|
||||
result.append(",");
|
||||
}
|
||||
result.append("\n");
|
||||
}
|
||||
|
||||
result.append(closeIndent).append(suffix);
|
||||
|
||||
String wrapped = result.toString();
|
||||
if (getVisualLength(indent + prefix) <= maxWidth) {
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the opening paren of the outermost method/constructor call
|
||||
* that should trigger argument-aware wrapping.
|
||||
* Looks for patterns: {@code identifier(}, {@code new Type(}, {@code .method(}
|
||||
*
|
||||
* @return index of the '(' or -1 if no suitable call found
|
||||
*/
|
||||
private int findOutermostCallParen(String content) {
|
||||
int bestIdx = -1;
|
||||
boolean inString = false;
|
||||
char stringChar = 0;
|
||||
|
||||
for (int i = 0; i < content.length(); i++) {
|
||||
char c = content.charAt(i);
|
||||
char prev = i > 0 ? content.charAt(i - 1) : ' ';
|
||||
|
||||
if ((c == '"' || c == '\'') && prev != '\\') {
|
||||
if (!inString) {
|
||||
inString = true;
|
||||
stringChar = c;
|
||||
} else if (c == stringChar) {
|
||||
inString = false;
|
||||
}
|
||||
}
|
||||
if (inString) continue;
|
||||
|
||||
if (c == '(') {
|
||||
if (i > 0 && (Character.isJavaIdentifierPart(content.charAt(i - 1)) ||
|
||||
content.charAt(i - 1) == '>')) {
|
||||
bestIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bestIdx;
|
||||
}
|
||||
|
||||
private int findMatchingClose(String content, int openIdx) {
|
||||
int depth = 1;
|
||||
boolean inString = false;
|
||||
char stringChar = 0;
|
||||
|
||||
for (int i = openIdx + 1; i < content.length(); i++) {
|
||||
char c = content.charAt(i);
|
||||
char prev = i > 0 ? content.charAt(i - 1) : ' ';
|
||||
|
||||
if ((c == '"' || c == '\'') && prev != '\\') {
|
||||
if (!inString) {
|
||||
inString = true;
|
||||
stringChar = c;
|
||||
} else if (c == stringChar) {
|
||||
inString = false;
|
||||
}
|
||||
}
|
||||
if (inString) continue;
|
||||
|
||||
if (c == '(') depth++;
|
||||
else if (c == ')') {
|
||||
depth--;
|
||||
if (depth == 0) return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split argument body by top-level commas, preserving nested parens,
|
||||
* brackets, braces, strings, and lambda bodies.
|
||||
*/
|
||||
private List<String> splitArguments(String argsBody) {
|
||||
List<String> args = new ArrayList<>();
|
||||
StringBuilder current = new StringBuilder();
|
||||
int depth = 0;
|
||||
boolean inString = false;
|
||||
char stringChar = 0;
|
||||
|
||||
for (int i = 0; i < argsBody.length(); i++) {
|
||||
char c = argsBody.charAt(i);
|
||||
char prev = i > 0 ? argsBody.charAt(i - 1) : ' ';
|
||||
|
||||
if ((c == '"' || c == '\'') && prev != '\\') {
|
||||
if (!inString) {
|
||||
inString = true;
|
||||
stringChar = c;
|
||||
} else if (c == stringChar) {
|
||||
inString = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (inString) {
|
||||
current.append(c);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '(' || c == '[' || c == '{') depth++;
|
||||
else if (c == ')' || c == ']' || c == '}') depth--;
|
||||
|
||||
if (c == ',' && depth == 0) {
|
||||
args.add(current.toString());
|
||||
current = new StringBuilder();
|
||||
continue;
|
||||
}
|
||||
|
||||
current.append(c);
|
||||
}
|
||||
|
||||
if (current.length() > 0) {
|
||||
args.add(current.toString());
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
private String trimLeading(String s) {
|
||||
int start = 0;
|
||||
while (start < s.length() && Character.isWhitespace(s.charAt(start))) {
|
||||
@@ -1943,6 +2338,10 @@ public class FormatHelper {
|
||||
}
|
||||
}
|
||||
|
||||
private static final String[] DECLARATION_BREAK_KEYWORDS = {
|
||||
"extends", "implements", "throws", "permits"
|
||||
};
|
||||
|
||||
/**
|
||||
* Find good positions to break a line.
|
||||
*/
|
||||
@@ -1988,20 +2387,51 @@ public class FormatHelper {
|
||||
points.add(new BreakPoint(i + 1, 1 + depth));
|
||||
}
|
||||
|
||||
// Arrow operators (-> and =>) are atomic — never break inside them
|
||||
if ((c == '-' || c == '=') && i + 1 < content.length() && content.charAt(i + 1) == '>') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (settings.wrapAfterOperator) {
|
||||
// After binary operators
|
||||
if ((c == '+' || c == '-') && i > 0 && i < content.length() - 1) {
|
||||
char next = content.charAt(i + 1);
|
||||
if (prev != '(' && prev != '[' && prev != ',' && prev != '=' &&
|
||||
next != '+' && next != '-' && next != '=') {
|
||||
next != '+' && next != '-' && next != '=' && next != '>') {
|
||||
points.add(new BreakPoint(i + 1, 3 + depth));
|
||||
}
|
||||
}
|
||||
if (c == '&' && i + 1 < content.length() && content.charAt(i + 1) == '&') {
|
||||
points.add(new BreakPoint(i + 2, 2 + depth));
|
||||
i++; // skip second &
|
||||
continue;
|
||||
}
|
||||
if (c == '|' && i + 1 < content.length() && content.charAt(i + 1) == '|') {
|
||||
points.add(new BreakPoint(i + 2, 2 + depth));
|
||||
i++; // skip second |
|
||||
continue;
|
||||
}
|
||||
// Single & as type intersection operator (e.g. T extends A & B)
|
||||
if (c == '&' && i > 0 && i < content.length() - 1
|
||||
&& content.charAt(i + 1) != '&' && content.charAt(i + 1) != '=') {
|
||||
points.add(new BreakPoint(i + 1, 3 + depth));
|
||||
}
|
||||
if (c == '?' && depth == 0 && i > 0 && i < content.length() - 1) {
|
||||
points.add(new BreakPoint(i, 2));
|
||||
}
|
||||
if (c == ':' && depth == 0 && i > 0 && i < content.length() - 1) {
|
||||
if (prev != ':' && (i + 1 >= content.length() || content.charAt(i + 1) != ':')) {
|
||||
points.add(new BreakPoint(i, 2));
|
||||
}
|
||||
}
|
||||
if (c == '=' && depth == 0 && i > 0 && i < content.length() - 1) {
|
||||
char next = content.charAt(i + 1);
|
||||
if (prev != '=' && prev != '!' && prev != '<' && prev != '>' &&
|
||||
prev != '+' && prev != '-' && prev != '*' && prev != '/' &&
|
||||
prev != '%' && prev != '&' && prev != '|' && prev != '^' &&
|
||||
next != '=' && next != '>') {
|
||||
points.add(new BreakPoint(i + 1, 4 + depth));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2010,9 +2440,28 @@ public class FormatHelper {
|
||||
points.add(new BreakPoint(i, 2 + depth));
|
||||
}
|
||||
|
||||
// After opening brace
|
||||
if (c == '{' && i + 1 < content.length()) {
|
||||
points.add(new BreakPoint(i + 1, 1));
|
||||
// After opening brace (even when last char — allows break before {)
|
||||
if (c == '{') {
|
||||
if (i + 1 < content.length()) {
|
||||
points.add(new BreakPoint(i + 1, 1));
|
||||
}
|
||||
// Break before { so the brace can move to its own line
|
||||
if (i > 0) {
|
||||
points.add(new BreakPoint(i, 2));
|
||||
}
|
||||
}
|
||||
|
||||
// Break before declaration keywords (extends, implements, throws, permits)
|
||||
if (c == ' ' && i + 1 < content.length() && Character.isLetter(content.charAt(i + 1))) {
|
||||
for (String kw : DECLARATION_BREAK_KEYWORDS) {
|
||||
if (i + 1 + kw.length() <= content.length()
|
||||
&& content.substring(i + 1, i + 1 + kw.length()).equals(kw)
|
||||
&& (i + 1 + kw.length() >= content.length()
|
||||
|| !Character.isJavaIdentifierPart(content.charAt(i + 1 + kw.length())))) {
|
||||
points.add(new BreakPoint(i + 1, 2));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -157,9 +157,9 @@ public class IndentHelper {
|
||||
*
|
||||
* @param text The text to format
|
||||
* @param cursorPosition Current cursor position
|
||||
* @param viewportWidth Viewport width for line wrapping (0 = no wrapping)
|
||||
* @param maxLineLength Maximum line length in characters for wrapping (0 = no wrapping)
|
||||
*/
|
||||
public static FormatResult formatText(String text, int cursorPosition, int viewportWidth) {
|
||||
public static FormatResult formatText(String text, int cursorPosition, int maxLineLength) {
|
||||
// First pass: fix indentation
|
||||
String indented = formatIndentation(text, cursorPosition);
|
||||
|
||||
@@ -167,19 +167,17 @@ public class IndentHelper {
|
||||
FormatHelper helper = new FormatHelper();
|
||||
FormatHelper.FormatSettings settings = helper.getSettings();
|
||||
|
||||
// Enable wrapping if viewport width is provided
|
||||
if (viewportWidth > 0) {
|
||||
// Enable wrapping if max line length is provided
|
||||
if (maxLineLength > 0) {
|
||||
settings.wrapLongLines = true;
|
||||
settings.wrapComments = true;
|
||||
// Use 75% of viewport width as max line length for some margin
|
||||
int charWidth = 6; // Approximate character width
|
||||
settings.maxLineLength = Math.max(60, (int) (viewportWidth * 0.8f / charWidth));
|
||||
settings.maxLineLength = maxLineLength;
|
||||
}
|
||||
|
||||
String formatted = helper.format(indented);
|
||||
|
||||
// Apply wrapping if enabled
|
||||
if (viewportWidth > 0 && settings.wrapLongLines) {
|
||||
if (maxLineLength > 0 && settings.wrapLongLines) {
|
||||
formatted = helper.wrapLines(formatted, settings.maxLineLength);
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,9 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
|
||||
// Match scoring
|
||||
private int matchScore = 0; // How well this matches the query
|
||||
private int[] matchIndices; // Indices of matched characters for highlighting
|
||||
|
||||
|
||||
private int color = -1;
|
||||
|
||||
private AutocompleteItem(String name, String searchName, String insertText, Kind kind, String typeLabel,
|
||||
TypeInfo typeLabelTypeInfo, String signature, String documentation, Object sourceData,
|
||||
boolean deprecated, boolean requiresImport, String importPath, int inheritanceDepth) {
|
||||
@@ -597,7 +599,8 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
|
||||
public String getImportPath() { return importPath; }
|
||||
public int getMatchScore() { return matchScore; }
|
||||
public int[] getMatchIndices() { return matchIndices; }
|
||||
|
||||
public int getColor() { return color; };
|
||||
public AutocompleteItem setColor(int col){ this.color = col;return this; }
|
||||
/**
|
||||
* Get the display name for a type, including generic arguments.
|
||||
* Uses the unified getDisplayName() method which handles:
|
||||
@@ -757,12 +760,14 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
|
||||
private String insertText;
|
||||
private Kind kind = Kind.FIELD;
|
||||
private String typeLabel = "";
|
||||
private TypeInfo typeInfo;
|
||||
private String signature;
|
||||
private String documentation;
|
||||
private Object sourceData;
|
||||
private boolean deprecated = false;
|
||||
private boolean requiresImport = false;
|
||||
private String importPath = null;
|
||||
private int color = -1;
|
||||
|
||||
public Builder name(String name) {
|
||||
this.name = name;
|
||||
@@ -788,6 +793,11 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
|
||||
this.typeLabel = typeLabel;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder typeInfo(TypeInfo typeInfo) {
|
||||
this.typeInfo = typeInfo;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder signature(String signature) {
|
||||
this.signature = signature;
|
||||
@@ -818,13 +828,18 @@ public class AutocompleteItem implements Comparable<AutocompleteItem> {
|
||||
this.importPath = importPath;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder color(int color) {
|
||||
this.color = color;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AutocompleteItem build() {
|
||||
if (insertText == null) {
|
||||
insertText = name;
|
||||
}
|
||||
return new AutocompleteItem(name, searchName, insertText, kind, typeLabel,
|
||||
null, signature, documentation, sourceData, deprecated, requiresImport, importPath, -1);
|
||||
typeInfo, signature, documentation, sourceData, deprecated, requiresImport, importPath, -1).setColor(color);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -459,11 +459,15 @@ public class AutocompleteMenu extends Gui {
|
||||
|
||||
TypeInfo type = item.getTypeInfo();
|
||||
int col = type != null ? type.getTokenType().getHexColor() : DIM_TEXT_COLOR;
|
||||
drawTypeLabel(typeLabel, typeLabelX, textY, col, type);
|
||||
drawTypeLabel(item, typeLabel, typeLabelX, textY, col, type);
|
||||
}
|
||||
}
|
||||
|
||||
public int getColor(AutocompleteItem item) {
|
||||
int col = item.getColor();
|
||||
if (col != -1)
|
||||
return col;
|
||||
|
||||
if (item.isInheritedObjectMethod() || item.isDeprecated())
|
||||
return DIM_TEXT_COLOR;
|
||||
|
||||
@@ -631,8 +635,8 @@ public class AutocompleteMenu extends Gui {
|
||||
return text;
|
||||
}
|
||||
|
||||
private void drawTypeLabel(String typeLabel, int x, int y, int typeColor, TypeInfo typeInfo) {
|
||||
if (typeInfo == null) {
|
||||
private void drawTypeLabel(AutocompleteItem item, String typeLabel, int x, int y, int typeColor, TypeInfo typeInfo) {
|
||||
if (typeInfo == null || item.getKind() == AutocompleteItem.Kind.CLASS) { //draw package on right
|
||||
drawSimpleTypeWithArraySuffix(typeLabel, x, y, typeColor);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import noppes.npcs.client.gui.util.script.interpreter.ScriptDocument;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
|
||||
@@ -434,10 +435,12 @@ public class JavaAutocompleteProvider implements AutocompleteProvider {
|
||||
.kind(type.getKind() == TypeInfo.Kind.ENUM ?
|
||||
AutocompleteItem.Kind.ENUM : AutocompleteItem.Kind.CLASS)
|
||||
.typeLabel(type.getPackageName())
|
||||
.typeInfo(type)
|
||||
.signature(type.getFullName())
|
||||
.sourceData(type)
|
||||
.requiresImport(true)
|
||||
.importPath(fullName)
|
||||
.color(TokenType.UNUSED_IMPORT.getHexColor())
|
||||
.build();
|
||||
items.add(item);
|
||||
existingSimpleNames.add(type.getSimpleName());
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter;
|
||||
|
||||
import noppes.npcs.client.gui.util.script.interpreter.token.Token;
|
||||
|
||||
/**
|
||||
* Centralized error representation for the script document.
|
||||
* Captures all validation errors (method calls, assignments, method declarations, type declarations)
|
||||
* into a single list for generic processing.
|
||||
*
|
||||
* <p>Each error tracks:
|
||||
* <ul>
|
||||
* <li>{@code token} - the associated token (may be null for span-based errors)</li>
|
||||
* <li>{@code startPos} - global start offset of the error span</li>
|
||||
* <li>{@code endPos} - global end offset of the error span</li>
|
||||
* <li>{@code message} - human-readable error description</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class DocumentError {
|
||||
|
||||
private final Token token;
|
||||
private final int startPos;
|
||||
private final int endPos;
|
||||
private final String message;
|
||||
|
||||
/**
|
||||
* Create a new document error.
|
||||
*
|
||||
* @param token The associated token, or null if this error is span-based
|
||||
* @param startPos Global start offset of the error span
|
||||
* @param endPos Global end offset of the error span
|
||||
* @param message Human-readable error description
|
||||
*/
|
||||
public DocumentError(Token token, int startPos, int endPos, String message) {
|
||||
this.token = token;
|
||||
this.startPos = startPos;
|
||||
this.endPos = endPos;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public DocumentError(int startPos, int endPos, String message) {
|
||||
this.token = null;
|
||||
this.startPos = startPos;
|
||||
this.endPos = endPos;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public Token getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public int getStartPos() {
|
||||
return startPos;
|
||||
}
|
||||
|
||||
public int getEndPos() {
|
||||
return endPos;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DocumentError{" +
|
||||
"startPos=" + startPos +
|
||||
", endPos=" + endPos +
|
||||
", message='" + message + '\'' +
|
||||
", token=" + (token != null ? token.getText() : "null") +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,14 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter;
|
||||
|
||||
import noppes.npcs.client.ClientProxy;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.AssignmentInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.ScriptTypeInfo;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
/**
|
||||
* Helper class for rendering error underlines in script editor lines.
|
||||
* Handles the repetitive calculation of underline positions and drawing of curly underlines.
|
||||
* Renders underlines from the document's centralized error list ({@link DocumentError}).
|
||||
*
|
||||
* <p>Error collection happens during analysis in {@link ScriptDocument#formatCodeText()}.
|
||||
* This renderer only draws; it does not detect or collect errors.
|
||||
*/
|
||||
public class ErrorUnderlineRenderer {
|
||||
private static final int ERROR_COLOR = 0xFF5555;
|
||||
@@ -32,6 +30,8 @@ public class ErrorUnderlineRenderer {
|
||||
|
||||
/**
|
||||
* Draw error underlines for all validation errors in the document that intersect the given line.
|
||||
* Iterates over the document's centralized error list and draws underlines for each error
|
||||
* whose span intersects this line.
|
||||
*
|
||||
* @param doc The script document containing all errors
|
||||
* @param lineStartX X coordinate where the line starts rendering
|
||||
@@ -47,125 +47,10 @@ public class ErrorUnderlineRenderer {
|
||||
|
||||
if (doc == null)
|
||||
return;
|
||||
|
||||
|
||||
// Check all method calls in the document
|
||||
for (MethodCallInfo call : doc.getMethodCalls()) {
|
||||
// Skip method declarations that were erroneously recorded as calls
|
||||
boolean isDeclaration = false;
|
||||
int methodStart = call.getMethodNameStart();
|
||||
for (MethodInfo mi : doc.getAllMethods()) {
|
||||
//!call.isConstructor for enum declarations
|
||||
if (!call.isConstructor() && mi.getDeclarationOffset() <= methodStart && mi.getBodyStart() >= methodStart) {
|
||||
isDeclaration = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isDeclaration)
|
||||
continue;
|
||||
|
||||
// Skip if this call doesn't intersect this line
|
||||
if (call.getCloseParenOffset() < lineStart || call.getOpenParenOffset() > lineEnd)
|
||||
continue;
|
||||
|
||||
// Handle arg count errors (underline the method name)
|
||||
if (call.hasArgCountError()) {
|
||||
int methodEnd = methodStart + call.getMethodName().length();
|
||||
drawUnderlineForSpan(methodStart, methodEnd, lineStartX, baselineY,
|
||||
lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
} else if (call.hasArgTypeError()) {
|
||||
// Handle return type mismatch (underline the method name) - currently commented out
|
||||
// if (call.hasReturnTypeMismatch()) { ... }
|
||||
|
||||
// Handle arg type errors (underline specific arguments)
|
||||
|
||||
for (MethodCallInfo.ArgumentTypeError error : call.getArgumentTypeErrors()) {
|
||||
MethodCallInfo.Argument arg = error.getArg();
|
||||
drawUnderlineForSpan(arg.getStartOffset(), arg.getEndOffset(),
|
||||
lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
} else if(call.hasError()){
|
||||
// Handle other call errors (underline the whole call)
|
||||
drawUnderlineForSpan(call.getMethodNameStart(), call.getCloseParenOffset() + 1,
|
||||
lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
// Check all field accesses in the document (currently commented out)
|
||||
// for (FieldAccessInfo access : doc.getFieldAccesses()) { ... }
|
||||
|
||||
// Check all errored assignments in the document
|
||||
for (AssignmentInfo assign : doc.getAllErroredAssignments()) {
|
||||
int underlineStart, underlineEnd;
|
||||
|
||||
if (assign.isLhsError()) {
|
||||
underlineStart = assign.getLhsStart();
|
||||
underlineEnd = assign.getLhsEnd();
|
||||
} else if (assign.isRhsError()) {
|
||||
underlineStart = assign.getRhsStart();
|
||||
underlineEnd = assign.getRhsEnd();
|
||||
} else if (assign.isFullLineError()) {
|
||||
underlineStart = assign.getStatementStart();
|
||||
underlineEnd = assign.getRhsEnd();
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
drawUnderlineForSpan(underlineStart, underlineEnd, lineStartX, baselineY,
|
||||
lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
|
||||
// Check all method declarations for errors
|
||||
for (MethodInfo method : doc.getAllMethods()) {
|
||||
if (!method.isDeclaration() || !method.hasError())
|
||||
continue;
|
||||
|
||||
// Handle return statement type errors
|
||||
if (method.hasReturnStatementErrors()) {
|
||||
for (MethodInfo.ReturnStatementError returnError : method.getReturnStatementErrors()) {
|
||||
drawUnderlineForSpan(returnError.getStartOffset(), returnError.getEndOffset(),
|
||||
lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle missing return error (underline the method name)
|
||||
else if (method.hasMissingReturnError()) {
|
||||
int methodNameStart = method.getNameOffset();
|
||||
int methodNameEnd = methodNameStart + method.getName().length();
|
||||
drawUnderlineForSpan(methodNameStart, methodNameEnd, lineStartX, baselineY,
|
||||
lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
// Handle parameter errors
|
||||
else if (method.hasParameterErrors()) {
|
||||
for (MethodInfo.ParameterError paramError : method.getParameterErrors()) {
|
||||
FieldInfo param = paramError.getParameter();
|
||||
if (param == null || param.getDeclarationOffset() < 0)
|
||||
continue;
|
||||
|
||||
int paramStart = param.getDeclarationOffset();
|
||||
int paramEnd = paramStart + param.getName().length();
|
||||
drawUnderlineForSpan(paramStart, paramEnd, lineStartX, baselineY,
|
||||
lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle all other errors
|
||||
else if (method.hasError()) {
|
||||
drawUnderlineForSpan(method.getFullDeclarationOffset(), method.getDeclarationEnd(), lineStartX,
|
||||
baselineY, lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
for(ScriptTypeInfo types : doc.getScriptTypes()){
|
||||
if(!types.hasError())
|
||||
continue;
|
||||
|
||||
int typeStart = types.getDeclarationOffset();
|
||||
int typeEnd = types.getBodyStart();
|
||||
drawUnderlineForSpan(typeStart, typeEnd, lineStartX, baselineY,
|
||||
lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
for (DocumentError error : doc.getErrors()) {
|
||||
drawUnderlineForSpan(error.getStartPos(), error.getEndPos(),
|
||||
lineStartX, baselineY, lineText, lineStart, lineEnd, ERROR_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -370,8 +370,9 @@ public class FieldChainMarker {
|
||||
if (!currentType.hasField(segment)) {
|
||||
// Field not found — check if the segment names an inner class.
|
||||
// This handles chains like Outer.Inner where Inner is a nested type, not a field.
|
||||
if (currentType instanceof ScriptTypeInfo) {
|
||||
ScriptTypeInfo innerClass = ((ScriptTypeInfo) currentType).getInnerClass(segment);
|
||||
TypeInfo rawType = currentType.getRawType();
|
||||
if (rawType instanceof ScriptTypeInfo) {
|
||||
ScriptTypeInfo innerClass = ((ScriptTypeInfo) rawType).getInnerClass(segment);
|
||||
if (innerClass != null) {
|
||||
return new MarkResult(
|
||||
new ScriptLine.Mark(pos[0], pos[1], innerClass.getTokenType(), innerClass),
|
||||
|
||||
@@ -12,9 +12,9 @@ import java.util.regex.Pattern;
|
||||
class LoopVariableParser {
|
||||
|
||||
private static final Pattern ENHANCED_FOR = Pattern.compile(
|
||||
"\\bfor\\s*\\(\\s*([A-Za-z_][\\w.<>\\[\\] \\t]*?(?:\\[\\s*\\])*)\\s+(\\w+)\\s*:\\s*([^)]+)\\)");
|
||||
"\\bfor\\s*\\(\\s*([A-Za-z_][\\w.<>,\\[\\] \\t\\n\\r]*?(?:\\[\\s*\\])*)\\s+(\\w+)\\s*:\\s*([^)]+)\\)");
|
||||
private static final Pattern CLASSIC_FOR = Pattern.compile(
|
||||
"\\bfor\\s*\\(\\s*([A-Za-z_][\\w.<>\\[\\] \\t]*?(?:\\[\\s*\\])*)\\s+(\\w+)\\s*=");
|
||||
"\\bfor\\s*\\(\\s*([A-Za-z_][\\w.<>,\\[\\] \\t\\n\\r]*?(?:\\[\\s*\\])*)\\s+(\\w+)\\s*=");
|
||||
private static final Pattern FOR_IN = Pattern.compile(
|
||||
"\\bfor\\s*\\(\\s*(?:var|let|const)\\s+(\\w+)\\s+in\\s+([^)]+)\\)");
|
||||
private static final Pattern FOR_OF = Pattern.compile(
|
||||
|
||||
@@ -4,6 +4,7 @@ import noppes.npcs.client.ClientProxy;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.token.Token;
|
||||
@@ -180,6 +181,14 @@ public class ScriptLine {
|
||||
public void applyTokenMetadata(Token token, Object metadata) {
|
||||
if (metadata instanceof TypeInfo) {
|
||||
token.setTypeInfo((TypeInfo) metadata);
|
||||
} else if (metadata instanceof TypeParamInfo) {
|
||||
TypeParamInfo typeParam = (TypeParamInfo) metadata;
|
||||
TypeInfo boundType = typeParam.getBoundTypeInfo();
|
||||
if (boundType != null) {
|
||||
token.setTypeInfo(TypeInfo.typeParameter(typeParam.getName(), boundType));
|
||||
} else {
|
||||
token.setTypeInfo(TypeInfo.typeParameter(typeParam.getName()));
|
||||
}
|
||||
} else if (metadata instanceof MethodCallInfo) {
|
||||
MethodCallInfo callInfo = (MethodCallInfo) metadata;
|
||||
if (callInfo.isConstructor()) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.field;
|
||||
|
||||
import noppes.npcs.client.gui.util.script.ScopeInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodCallInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeChecker;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
|
||||
|
||||
@@ -139,8 +140,8 @@ public class AssignmentInfo {
|
||||
// Check type compatibility
|
||||
if (targetType != null && sourceType != null) {
|
||||
if (!TypeChecker.isTypeCompatible(targetType, sourceType)) {
|
||||
this.requiredType = targetType.getSimpleName();
|
||||
this.providedType = sourceType.getSimpleName();
|
||||
this.requiredType = MethodCallInfo.getTypeDisplayName(targetType);
|
||||
this.providedType = MethodCallInfo.getTypeDisplayName(sourceType);
|
||||
setError(ErrorType.TYPE_MISMATCH, buildTypeMismatchMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +160,8 @@ public class EnumConstantInfo {
|
||||
List<MethodCallInfo.Argument> arguments = ScriptDocument.INSTANCE.parseMethodArguments(
|
||||
openParenPos + 1,
|
||||
closeParenPos,
|
||||
null
|
||||
null,
|
||||
enumType
|
||||
);
|
||||
|
||||
// Find matching constructor
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package noppes.npcs.client.gui.util.script.interpreter.hover;
|
||||
|
||||
import noppes.npcs.client.gui.util.script.interpreter.*;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.AssignmentInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldAccessInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocParamTag;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.jsdoc.JSDocReturnTag;
|
||||
@@ -153,6 +153,7 @@ public class TokenHoverInfo {
|
||||
case INTERFACE_DECL:
|
||||
case ENUM_DECL:
|
||||
case TYPE_DECL:
|
||||
case GENERIC_TYPE_PARAM:
|
||||
info.extractClassInfo(token);
|
||||
break;
|
||||
|
||||
@@ -212,313 +213,40 @@ public class TokenHoverInfo {
|
||||
// ==================== EXTRACTION METHODS ====================
|
||||
|
||||
private void extractErrors(Token token) {
|
||||
// Check if this token is part of a method call argument (positional lookup)
|
||||
MethodCallInfo containingCall = findMethodCallContainingPosition(token);
|
||||
if (containingCall != null) {
|
||||
MethodCallInfo.Argument containingArg = findArgumentContainingPosition(containingCall, token.getGlobalStart());
|
||||
if (containingArg != null) {
|
||||
// Show only this argument's specific error
|
||||
MethodCallInfo.ArgumentTypeError argError = findArgumentError(containingCall, containingArg);
|
||||
if (argError != null) {
|
||||
errors.add(argError.getMessage());
|
||||
return; // Only show argument error, not method-level errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show method-level errors if this is the method name itself
|
||||
MethodCallInfo callInfo = token.isEnumConstant()? containingCall : token.getMethodCallInfo();
|
||||
if (callInfo != null) {
|
||||
if (callInfo.hasArgCountError()) {
|
||||
errors.add(callInfo.getErrorMessage());
|
||||
}
|
||||
if (callInfo.hasArgTypeError()) {
|
||||
for (MethodCallInfo.ArgumentTypeError error : callInfo.getArgumentTypeErrors()) {
|
||||
errors.add(error.getMessage());
|
||||
}
|
||||
}
|
||||
if (callInfo.hasReturnTypeMismatch()) {
|
||||
errors.add(callInfo.getErrorMessage());
|
||||
}
|
||||
if (callInfo.hasStaticAccessError()) {
|
||||
errors.add(callInfo.getErrorMessage());
|
||||
}
|
||||
if (callInfo.getErrorType() == MethodCallInfo.ErrorType.UNRESOLVED_METHOD) {
|
||||
errors.add(callInfo.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Show field access errors
|
||||
FieldAccessInfo fieldAccessInfo = token.getFieldAccessInfo();
|
||||
if (fieldAccessInfo != null && fieldAccessInfo.hasError()) {
|
||||
errors.add(fieldAccessInfo.getErrorMessage());
|
||||
}
|
||||
|
||||
// Show assignment errors (type mismatch, final reassignment, etc.)
|
||||
// Search through FieldInfo's assignments by position
|
||||
AssignmentInfo assignmentInfo = findAssignmentContainingPosition(token);
|
||||
if (assignmentInfo != null && assignmentInfo.hasError()) {
|
||||
errors.add(assignmentInfo.getErrorMessage());
|
||||
}
|
||||
|
||||
// Show unresolved field errors
|
||||
FieldInfo fieldInfo = token.getFieldInfo();
|
||||
if (fieldInfo != null && !fieldInfo.isResolved()) {
|
||||
errors.add("Cannot resolve symbol '" + token.getText() + "'");
|
||||
}
|
||||
|
||||
// Show method declaration errors (missing return, parameter errors, return type errors)
|
||||
MethodInfo methodDecl = findMethodDeclarationContainingPosition(token);
|
||||
if (methodDecl != null && methodDecl.hasError()) {
|
||||
int tokenStart = token.getGlobalStart();
|
||||
int tokenEnd = token.getGlobalEnd();
|
||||
|
||||
// If hovering over the method name, show missing return error
|
||||
if (methodDecl.hasMissingReturnError()) {
|
||||
int methodNameStart = methodDecl.getNameOffset();
|
||||
int methodNameEnd = methodNameStart + methodDecl.getName().length();
|
||||
|
||||
if (tokenStart >= methodNameStart && tokenEnd <= methodNameEnd) {
|
||||
errors.add(methodDecl.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// If hovering over a parameter with an error, show that error
|
||||
else if (methodDecl.hasParameterErrors()) {
|
||||
for (MethodInfo.ParameterError paramError : methodDecl.getParameterErrors()) {
|
||||
FieldInfo param = paramError.getParameter();
|
||||
if (param != null && param.getDeclarationOffset() >= 0) {
|
||||
int paramStart = param.getDeclarationOffset();
|
||||
int paramEnd = paramStart + param.getName().length();
|
||||
|
||||
if (tokenStart >= paramStart && tokenEnd <= paramEnd) {
|
||||
errors.add(paramError.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If hovering over a return statement with a type error, show that error
|
||||
else if (methodDecl.hasReturnStatementErrors()) {
|
||||
for (MethodInfo.ReturnStatementError returnError : methodDecl.getReturnStatementErrors()) {
|
||||
int returnStart = returnError.getStartOffset();
|
||||
int returnEnd = returnError.getEndOffset();
|
||||
|
||||
if (tokenStart >= returnStart && tokenEnd <= returnEnd) {
|
||||
errors.add(returnError.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// All other errors
|
||||
else if (methodDecl.hasError()) {
|
||||
int declStart = methodDecl.getFullDeclarationOffset();
|
||||
int declEnd = methodDecl.getDeclarationEnd();
|
||||
|
||||
if (tokenStart >= declStart && tokenEnd <= declEnd) {
|
||||
errors.add(methodDecl.getErrorMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ScriptTypeInfo scriptType = findScriptTypeContainingPosition(token);
|
||||
if (scriptType != null && scriptType.hasError()) {
|
||||
// Missing interface method errors
|
||||
for (ScriptTypeInfo.MissingMethodError err : scriptType.getMissingMethodErrors()) {
|
||||
errors.add(err.getMessage());
|
||||
}
|
||||
// Constructor mismatch errors
|
||||
for (ScriptTypeInfo.ConstructorMismatchError err : scriptType.getConstructorMismatchErrors()) {
|
||||
errors.add(err.getMessage());
|
||||
}
|
||||
// General error message
|
||||
if (scriptType.getErrorMessage() != null) {
|
||||
errors.add(scriptType.getErrorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
EnumConstantInfo enumConst = findEnumConstantContainingPosition(token);
|
||||
if (enumConst != null && enumConst.hasError()) {
|
||||
errors.add(enumConst.getErrorMessage());
|
||||
}
|
||||
|
||||
if(token.getType() == TokenType.UNDEFINED_VAR)
|
||||
if (token.getType() == TokenType.UNDEFINED_VAR)
|
||||
errors.add("Cannot resolve symbol '" + token.getText() + "'");
|
||||
|
||||
TokenErrorMessage msg = token.getErrorMessage();
|
||||
if (msg != null && !msg.getMessage().isEmpty()) {
|
||||
if(msg.clearOtherErrors)
|
||||
if (msg.clearOtherErrors)
|
||||
errors.clear();
|
||||
|
||||
|
||||
errors.add(msg.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an assignment that contains this token's position.
|
||||
* Searches through all assignments (script fields and external fields).
|
||||
*/
|
||||
private AssignmentInfo findAssignmentContainingPosition(Token token) {
|
||||
ScriptLine line = token.getParentLine();
|
||||
if (line == null || line.getParent() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ScriptDocument doc = line.getParent();
|
||||
int tokenStart = token.getGlobalStart();
|
||||
|
||||
// Use ScriptDocument's method which handles all prioritization
|
||||
return doc.findAssignmentAtPosition(tokenStart);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the method call that contains this token's position within its argument list.
|
||||
*/
|
||||
private MethodCallInfo findMethodCallContainingPosition(Token token) {
|
||||
ScriptLine line = token.getParentLine();
|
||||
if (line == null || line.getParent() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ScriptDocument doc = line.getParent();
|
||||
int tokenStart = token.getGlobalStart();
|
||||
|
||||
for (MethodCallInfo call : doc.getMethodCalls()) {
|
||||
boolean isWithinName = tokenStart >= call.getMethodNameStart() && tokenStart <= call.getMethodNameEnd();
|
||||
|
||||
// If this is an enum constant, return methodCall on name itself
|
||||
if (token.isEnumConstant() && isWithinName)
|
||||
return call;
|
||||
|
||||
// Check if token is within the argument list
|
||||
if (tokenStart >= call.getOpenParenOffset() && tokenStart <= call.getCloseParenOffset()) {
|
||||
// Make sure it's not the method name itself
|
||||
if (isWithinName) {
|
||||
continue;
|
||||
// Detailed error detection happens once in ScriptDocument.populateErrors();
|
||||
// hover just looks up by position.
|
||||
ScriptDocument doc = ScriptDocument.INSTANCE;
|
||||
if (doc != null) {
|
||||
int tokenStart = token.getGlobalStart();
|
||||
int tokenEnd = token.getGlobalEnd();
|
||||
for (DocumentError error : doc.getErrors()) {
|
||||
if (tokenStart < error.getEndPos() && tokenEnd > error.getStartPos()) {
|
||||
errors.add(error.getMessage());
|
||||
}
|
||||
return call;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the method declaration that contains this token's position.
|
||||
* Returns null if the token is not within a method declaration (header or body).
|
||||
*/
|
||||
private MethodInfo findMethodDeclarationContainingPosition(Token token) {
|
||||
ScriptLine line = token.getParentLine();
|
||||
if (line == null || line.getParent() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ScriptDocument doc = line.getParent();
|
||||
int tokenStart = token.getGlobalStart();
|
||||
|
||||
for (MethodInfo method : doc.getAllMethods()) {
|
||||
if (!method.isDeclaration())
|
||||
continue;
|
||||
|
||||
// Check if token is within the method declaration header OR body
|
||||
int methodStart = method.getFullDeclarationOffset();
|
||||
if (methodStart < 0) methodStart = method.getTypeOffset();
|
||||
int bodyEnd = method.getBodyEnd();
|
||||
|
||||
// Token is within the method (header + body)
|
||||
if (tokenStart >= methodStart && tokenStart <= bodyEnd) {
|
||||
return method;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private ScriptTypeInfo findScriptTypeContainingPosition(Token token) {
|
||||
ScriptLine line = token.getParentLine();
|
||||
if (line == null || line.getParent() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ScriptDocument doc = line.getParent();
|
||||
int tokenStart = token.getGlobalStart();
|
||||
|
||||
for (ScriptTypeInfo scriptType : doc.getScriptTypes()) {
|
||||
int typeStart = scriptType.getDeclarationOffset();
|
||||
int typeEnd = scriptType.getBodyStart();
|
||||
|
||||
// Token is within the type declaration
|
||||
if (tokenStart >= typeStart && tokenStart <= typeEnd) {
|
||||
return scriptType;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private EnumConstantInfo findEnumConstantContainingPosition(Token token) {
|
||||
ScriptLine line = token.getParentLine();
|
||||
if (line == null || line.getParent() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ScriptDocument doc = line.getParent();
|
||||
int tokenStart = token.getGlobalStart();
|
||||
|
||||
for (EnumConstantInfo enumConst : doc.getAllEnumConstants()) {
|
||||
int constStart = enumConst.getDeclarationOffset();
|
||||
int constEnd = constStart + enumConst.getName().length();
|
||||
|
||||
// Token is within the enum constant declaration
|
||||
if (tokenStart >= constStart && tokenStart <= constEnd) {
|
||||
return enumConst;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the argument that contains the given position.
|
||||
*/
|
||||
private MethodCallInfo.Argument findArgumentContainingPosition(MethodCallInfo callInfo, int position) {
|
||||
for (MethodCallInfo.Argument arg : callInfo.getArguments()) {
|
||||
if (position >= arg.getStartOffset() && position <= arg.getEndOffset()) {
|
||||
return arg;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the type error for a specific argument.
|
||||
*/
|
||||
private MethodCallInfo.ArgumentTypeError findArgumentError(MethodCallInfo callInfo, MethodCallInfo.Argument argument) {
|
||||
if (!callInfo.hasArgTypeError()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int argIndex = callInfo.getArguments().indexOf(argument);
|
||||
if (argIndex < 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (MethodCallInfo.ArgumentTypeError error : callInfo.getArgumentTypeErrors()) {
|
||||
if (error.getArgIndex() == argIndex) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private int getExpectedArgCount(MethodCallInfo callInfo) {
|
||||
MethodInfo method = callInfo.getResolvedMethod();
|
||||
if (method != null) {
|
||||
return method.getParameterCount();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
private void extractClassInfo(Token token) {
|
||||
TypeInfo typeInfo = token.getTypeInfo();
|
||||
if (typeInfo == null) return;
|
||||
|
||||
if (typeInfo.isTypeParameter()) {
|
||||
extractTypeParameterInfo(typeInfo);
|
||||
return;
|
||||
}
|
||||
|
||||
packageName = getPackageName(typeInfo);
|
||||
|
||||
@@ -557,6 +285,7 @@ public class TokenHoverInfo {
|
||||
: TokenType.IMPORTED_CLASS.getHexColor();
|
||||
// Render generics with correct segment colors if present
|
||||
addTypeSegments(typeInfo);
|
||||
addDeclaredTypeParamSegments(typeInfo);
|
||||
|
||||
// Extends
|
||||
Class<?> superclass = clazz.getSuperclass();
|
||||
@@ -616,8 +345,7 @@ public class TokenHoverInfo {
|
||||
: scriptType.getKind() == TypeInfo.Kind.ENUM ? TokenType.ENUM_DECL.getHexColor()
|
||||
: TokenType.IMPORTED_CLASS.getHexColor();
|
||||
addTypeSegments(typeInfo);
|
||||
|
||||
// Extends clause for ScriptTypeInfo
|
||||
addDeclaredTypeParamSegments(typeInfo);
|
||||
if (scriptType.hasSuperClass()) {
|
||||
addSegment(" extends ", TokenType.MODIFIER.getHexColor());
|
||||
TypeInfo superClass = scriptType.getSuperClass();
|
||||
@@ -688,6 +416,7 @@ public class TokenHoverInfo {
|
||||
iconIndicator = "I";
|
||||
addSegment("interface ", TokenType.MODIFIER.getHexColor());
|
||||
addTypeSegments(typeInfo);
|
||||
addDeclaredTypeParamSegments(typeInfo);
|
||||
|
||||
if (jsType.getExtendsType() != null) {
|
||||
addSegment(" extends ", TokenType.MODIFIER.getHexColor());
|
||||
@@ -718,6 +447,22 @@ public class TokenHoverInfo {
|
||||
}
|
||||
}
|
||||
|
||||
private void extractTypeParameterInfo(TypeInfo typeInfo) {
|
||||
iconIndicator = "T";
|
||||
String paramName = typeInfo.getTypeParameterName();
|
||||
|
||||
addSegment("type parameter ", TokenType.MODIFIER.getHexColor());
|
||||
addSegment("<", TokenType.DEFAULT.getHexColor());
|
||||
addSegment(paramName, TokenType.GENERIC_TYPE_PARAM.getHexColor());
|
||||
|
||||
TypeInfo bound = typeInfo.getBoundType();
|
||||
if (bound != null && bound.getJavaClass() != null && bound.getJavaClass() != Object.class) {
|
||||
addSegment(" extends ", TokenType.MODIFIER.getHexColor());
|
||||
addSegment(bound.getSimpleName(), getColorForTypeInfo(bound));
|
||||
}
|
||||
addSegment(">", TokenType.DEFAULT.getHexColor());
|
||||
}
|
||||
|
||||
private void extractMethodCallInfo(Token token) {
|
||||
MethodCallInfo callInfo = token.getMethodCallInfo();
|
||||
MethodInfo methodInfo = callInfo != null ? callInfo.getResolvedMethod() : token.getMethodInfo();
|
||||
@@ -769,7 +514,7 @@ public class TokenHoverInfo {
|
||||
buildBasicMethodDeclaration(methodInfo, containingType);
|
||||
return;
|
||||
}
|
||||
buildMethodDeclaration(methodInfo.getJavaMethod(), containingType);
|
||||
buildMethodDeclaration(methodInfo, containingType);
|
||||
extractJavadoc(methodInfo.getJavaMethod());
|
||||
return;
|
||||
}
|
||||
@@ -935,6 +680,9 @@ public class TokenHoverInfo {
|
||||
if (type == null)
|
||||
return null;
|
||||
|
||||
if (type.isTypeParameter())
|
||||
return null;
|
||||
|
||||
TypeInfo base = type.isArray() ? type.getElementType() : type;
|
||||
if (base == null) base = type;
|
||||
|
||||
@@ -1037,6 +785,29 @@ public class TokenHoverInfo {
|
||||
splitAndAddTypeName(typeName, getColorForTypeInfo(typeInfo));
|
||||
}
|
||||
|
||||
private void addDeclaredTypeParamSegments(TypeInfo typeInfo) {
|
||||
List<TypeParamInfo> params = typeInfo.getTypeParams();
|
||||
if (params == null || params.isEmpty()) return;
|
||||
if (typeInfo.isParameterized()) return;
|
||||
|
||||
addSegment("<", TokenType.DEFAULT.getHexColor());
|
||||
for (int i = 0; i < params.size(); i++) {
|
||||
if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor());
|
||||
TypeParamInfo param = params.get(i);
|
||||
addSegment(param.getName(), TokenType.GENERIC_TYPE_PARAM.getHexColor());
|
||||
if (param.getBoundTypeName() != null && !"Object".equals(param.getBoundTypeName())) {
|
||||
addSegment(" extends ", TokenType.MODIFIER.getHexColor());
|
||||
TypeInfo boundType = param.getBoundTypeInfo();
|
||||
if (boundType != null && boundType.isResolved()) {
|
||||
addTypeSegments(boundType);
|
||||
} else {
|
||||
addSegment(param.getBoundTypeName(), TokenType.IMPORTED_CLASS.getHexColor());
|
||||
}
|
||||
}
|
||||
}
|
||||
addSegment(">", TokenType.DEFAULT.getHexColor());
|
||||
}
|
||||
|
||||
private void splitAndAddTypeName(String typeName, int typeColor) {
|
||||
if (typeName == null || !typeName.endsWith("[]")) {
|
||||
addSegment(typeName, typeColor);
|
||||
@@ -1111,7 +882,8 @@ public class TokenHoverInfo {
|
||||
declaration.add(new TextSegment(text, color));
|
||||
}
|
||||
|
||||
private void buildMethodDeclaration(Method method, TypeInfo containingType) {
|
||||
private void buildMethodDeclaration(MethodInfo methodInfo, TypeInfo containingType) {
|
||||
Method method = methodInfo.getJavaMethod();
|
||||
int mods = method.getModifiers();
|
||||
|
||||
// Annotations (show @Contract if present, etc.)
|
||||
@@ -1128,9 +900,9 @@ public class TokenHoverInfo {
|
||||
if (Modifier.isSynchronized(mods)) addSegment("synchronized ", TokenType.MODIFIER.getHexColor());
|
||||
|
||||
// Return type - check for actual type color (handle array suffix coloring)
|
||||
Class<?> returnType = method.getReturnType();
|
||||
TypeInfo returnType = methodInfo.getReturnType();
|
||||
String returnTypeName = returnType.getSimpleName();
|
||||
splitAndAddTypeName(returnTypeName, getColorForTypeInfo(containingType));
|
||||
splitAndAddTypeName(returnTypeName, getColorForTypeInfo(methodInfo.getReturnType()));
|
||||
addSegment(" ", TokenType.DEFAULT.getHexColor());
|
||||
|
||||
// Method name
|
||||
@@ -1138,20 +910,19 @@ public class TokenHoverInfo {
|
||||
|
||||
// Parameters
|
||||
addSegment("(", TokenType.DEFAULT.getHexColor());
|
||||
Class<?>[] paramTypes = method.getParameterTypes();
|
||||
java.lang.reflect.Parameter[] params = method.getParameters();
|
||||
for (int i = 0; i < paramTypes.length; i++) {
|
||||
List<FieldInfo> params = methodInfo.getParameters();
|
||||
for (int i = 0; i < params.size(); i++) {
|
||||
if (i > 0) addSegment(", ", TokenType.DEFAULT.getHexColor());
|
||||
int paramTypeColor = getColorForClass(paramTypes[i]);
|
||||
String paramTypeName = paramTypes[i].getSimpleName();
|
||||
splitAndAddTypeName(paramTypeName, paramTypeColor);
|
||||
if (method.isVarArgs() && i == paramTypes.length - 1) {
|
||||
addSegment("...", TokenType.DEFAULT.getHexColor());
|
||||
FieldInfo param = params.get(i);
|
||||
TypeInfo paramType = param.getTypeInfo();
|
||||
if (paramType != null) {
|
||||
addTypeSegments(paramType);
|
||||
if (param.isVarArg()) {
|
||||
addSegment("...", TokenType.DEFAULT.getHexColor());
|
||||
}
|
||||
addSegment(" ", TokenType.DEFAULT.getHexColor());
|
||||
}
|
||||
addSegment(" ", TokenType.DEFAULT.getHexColor());
|
||||
// Try to get parameter name if available
|
||||
String paramName = params.length > i ? params[i].getName() : "arg" + i;
|
||||
addSegment(paramName, TokenType.PARAMETER.getHexColor());
|
||||
addSegment(param.getName(), TokenType.PARAMETER.getHexColor());
|
||||
}
|
||||
addSegment(")", TokenType.DEFAULT.getHexColor());
|
||||
}
|
||||
|
||||
@@ -47,9 +47,9 @@ final class DtsModScanner {
|
||||
for (DtsFileRef ref : dtsFiles) {
|
||||
domainCounts.put(ref.getDomain(), domainCounts.getOrDefault(ref.getDomain(), 0) + 1);
|
||||
}
|
||||
System.out.println("[JSTypeRegistry] Found " + dtsFiles.size() + " .d.ts files across " + domainCounts.size() + " domains");
|
||||
// System.out.println("[JSTypeRegistry] Found " + dtsFiles.size() + " .d.ts files across " + domainCounts.size() + " domains");
|
||||
for (Map.Entry<String, Integer> entry : domainCounts.entrySet()) {
|
||||
System.out.println("[JSTypeRegistry] Domain " + entry.getKey() + ": " + entry.getValue() + " files");
|
||||
// System.out.println("[JSTypeRegistry] Domain " + entry.getKey() + ": " + entry.getValue() + " files");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -204,31 +204,6 @@ public class JSTypeInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a type parameter to its bound TypeInfo.
|
||||
* For example, if this type has "T extends EntityPlayerMP", resolveTypeParam("T") returns the TypeInfo for EntityPlayerMP.
|
||||
* If no type parameter is found with that name, returns null.
|
||||
*/
|
||||
public TypeInfo resolveTypeParamToTypeInfo(String typeName) {
|
||||
TypeParamInfo param = getTypeParam(typeName);
|
||||
if (param != null) {
|
||||
return param.getBoundTypeInfo();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a type parameter to its bound type name (for backward compatibility).
|
||||
* @deprecated Use resolveTypeParamToTypeInfo instead
|
||||
*/
|
||||
@Deprecated
|
||||
public String resolveTypeParam(String typeName) {
|
||||
TypeParamInfo param = getTypeParam(typeName);
|
||||
if (param != null && param.getBoundTypeInfo() != null) {
|
||||
return param.getBoundTypeInfo().getSimpleName();
|
||||
}
|
||||
return typeName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a method by name, including inherited methods.
|
||||
|
||||
@@ -93,7 +93,7 @@ public class JSTypeRegistry {
|
||||
if (dtsFiles.isEmpty()) {
|
||||
Set<String> fallbackFiles = findAllDtsFilesInResources("assets/customnpcs/api");
|
||||
|
||||
System.out.println("[JSTypeRegistry] Found " + fallbackFiles.size() + " .d.ts files in resources");
|
||||
// System.out.println("[JSTypeRegistry] Found " + fallbackFiles.size() + " .d.ts files in resources");
|
||||
|
||||
if (fallbackFiles.contains("hooks.d.ts")) {
|
||||
loadResourceFile(parser, "hooks.d.ts");
|
||||
@@ -126,7 +126,7 @@ public class JSTypeRegistry {
|
||||
registerES5Builtins();
|
||||
|
||||
initialized = true;
|
||||
System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from resources");
|
||||
// System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from resources");
|
||||
} catch (Exception e) {
|
||||
System.err.println("[JSTypeRegistry] Failed to load type definitions from resources: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
@@ -276,7 +276,7 @@ public class JSTypeRegistry {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// File might not exist, that's ok
|
||||
System.out.println("[JSTypeRegistry] Could not load " + fileName + ": " + e.getMessage());
|
||||
// System.out.println("[JSTypeRegistry] Could not load " + fileName + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ public class JSTypeRegistry {
|
||||
resolveAllJSDocTypes();
|
||||
resolveInheritance();
|
||||
initialized = true;
|
||||
System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks");
|
||||
// System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks");
|
||||
} catch (IOException e) {
|
||||
System.err.println("[JSTypeRegistry] Failed to load type definitions: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
@@ -315,7 +315,7 @@ public class JSTypeRegistry {
|
||||
resolveAllJSDocTypes();
|
||||
resolveInheritance();
|
||||
initialized = true;
|
||||
System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from VSIX");
|
||||
// System.out.println("[JSTypeRegistry] Loaded " + types.size() + " types, " + hooks.size() + " hooks from VSIX");
|
||||
} catch (IOException e) {
|
||||
System.err.println("[JSTypeRegistry] Failed to load VSIX: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
@@ -360,7 +360,7 @@ public class JSTypeRegistry {
|
||||
if (!typesByJavaFqn.containsKey(javaFqn)) {
|
||||
typesByJavaFqn.put(javaFqn, type);
|
||||
} else {
|
||||
System.out.println("[JSTypeRegistry] Duplicate javaFqn " + javaFqn + " from " + getCurrentSource());
|
||||
// System.out.println("[JSTypeRegistry] Duplicate javaFqn " + javaFqn + " from " + getCurrentSource());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1048,13 +1048,13 @@ public class JSTypeRegistry {
|
||||
|
||||
private void logTypeCollision(String fullName, String incomingSource) {
|
||||
String existingSource = typeOrigins.getOrDefault(fullName, "unknown");
|
||||
System.out.println("[JSTypeRegistry] Duplicate type " + fullName + " from " + incomingSource + " (kept " + existingSource + ")");
|
||||
// System.out.println("[JSTypeRegistry] Duplicate type " + fullName + " from " + incomingSource + " (kept " + existingSource + ")");
|
||||
}
|
||||
|
||||
private void logAliasCollision(String alias, String existingType, String incomingType, String incomingSource) {
|
||||
String existingSource = aliasOrigins.getOrDefault(alias, "unknown");
|
||||
System.out.println("[JSTypeRegistry] Duplicate alias " + alias + " from " + incomingSource + " (kept " + existingSource + ")");
|
||||
System.out.println("[JSTypeRegistry] Alias " + alias + " existing=" + existingType + " incoming=" + incomingType);
|
||||
// System.out.println("[JSTypeRegistry] Duplicate alias " + alias + " from " + incomingSource + " (kept " + existingSource + ")");
|
||||
// System.out.println("[JSTypeRegistry] Alias " + alias + " existing=" + existingType + " incoming=" + incomingType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1162,9 +1162,9 @@ public class JSTypeRegistry {
|
||||
}
|
||||
|
||||
// Log merge details
|
||||
System.out.println("[JSTypeRegistry] Merged type " + existing.getFullName() +
|
||||
" with " + methodsMerged + " methods, " + fieldsMerged +
|
||||
" fields from " + incomingSource);
|
||||
// System.out.println("[JSTypeRegistry] Merged type " + existing.getFullName() +
|
||||
// " with " + methodsMerged + " methods, " + fieldsMerged +
|
||||
// " fields from " + incomingSource);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,16 +3,28 @@ package noppes.npcs.client.gui.util.script.interpreter.js_parser;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.type.TypeResolver;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Represents a generic type parameter like "T extends Entity".
|
||||
* Represents a generic type parameter like "T extends Entity" or "T extends Number & Comparable<T>".
|
||||
* Stores the parameter name and both the string representation (for deferred resolution)
|
||||
* and the resolved TypeInfo for the bound.
|
||||
*
|
||||
* Multiple bounds (e.g., {@code <T extends Number & Comparable<T>>}) are supported:
|
||||
* the primary bound is the first type after "extends", and additional bounds are
|
||||
* interface types separated by "&".
|
||||
*/
|
||||
public class TypeParamInfo {
|
||||
private final String name; // e.g., "T"
|
||||
private final String boundType; // Simple name like "EntityPlayerMP" (may be null)
|
||||
private final String fullBoundType; // Full name like "net.minecraft.entity.player.EntityPlayerMP" (may be null)
|
||||
private TypeInfo boundTypeInfo; // Resolved TypeInfo for the bound (resolved in Phase 2)
|
||||
private TypeInfo boundTypeInfo; // Resolved TypeInfo for the primary bound (resolved in Phase 2)
|
||||
|
||||
// Additional bounds from & syntax (e.g., Comparable<T> in "T extends Number & Comparable<T>")
|
||||
private final List<String> additionalBoundNames;
|
||||
private final List<TypeInfo> additionalBoundTypes;
|
||||
|
||||
/**
|
||||
* Constructor for parse-time (Phase 1) - stores string names only.
|
||||
@@ -22,6 +34,8 @@ public class TypeParamInfo {
|
||||
this.boundType = boundType;
|
||||
this.fullBoundType = fullBoundType;
|
||||
this.boundTypeInfo = null; // Will be resolved later
|
||||
this.additionalBoundNames = new ArrayList<>();
|
||||
this.additionalBoundTypes = new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getName() { return name; }
|
||||
@@ -30,6 +44,47 @@ public class TypeParamInfo {
|
||||
return boundTypeInfo;
|
||||
}
|
||||
|
||||
public void setBoundTypeInfo(TypeInfo boundTypeInfo) {
|
||||
this.boundTypeInfo = boundTypeInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an additional bound (from & syntax).
|
||||
* @param boundName The simple name of the additional bound type
|
||||
*/
|
||||
public void addAdditionalBound(String boundName) {
|
||||
additionalBoundNames.add(boundName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a resolved additional bound TypeInfo.
|
||||
* @param typeInfo The resolved TypeInfo for an additional bound
|
||||
*/
|
||||
public void addAdditionalBoundType(TypeInfo typeInfo) {
|
||||
additionalBoundTypes.add(typeInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of additional bound names (unresolved).
|
||||
*/
|
||||
public List<String> getAdditionalBoundNames() {
|
||||
return Collections.unmodifiableList(additionalBoundNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of resolved additional bound TypeInfos.
|
||||
*/
|
||||
public List<TypeInfo> getAdditionalBoundTypes() {
|
||||
return Collections.unmodifiableList(additionalBoundTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this type parameter has additional bounds (& syntax).
|
||||
*/
|
||||
public boolean hasAdditionalBounds() {
|
||||
return !additionalBoundNames.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the bound type using TypeResolver.
|
||||
* Called during Phase 2 after all types are loaded.
|
||||
@@ -58,11 +113,19 @@ public class TypeParamInfo {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder(name);
|
||||
if (boundTypeInfo != null) {
|
||||
return name + " extends " + boundTypeInfo.getDisplayName();
|
||||
sb.append(" extends ").append(boundTypeInfo.getDisplayName());
|
||||
} else if (boundType != null || fullBoundType != null) {
|
||||
return name + " extends " + (boundType != null ? boundType : fullBoundType);
|
||||
sb.append(" extends ").append(boundType != null ? boundType : fullBoundType);
|
||||
}
|
||||
return name;
|
||||
for (int i = 0; i < additionalBoundTypes.size(); i++) {
|
||||
sb.append(" & ").append(additionalBoundTypes.get(i).getDisplayName());
|
||||
}
|
||||
// Show unresolved additional bounds that don't have a resolved type yet
|
||||
for (int i = additionalBoundTypes.size(); i < additionalBoundNames.size(); i++) {
|
||||
sb.append(" & ").append(additionalBoundNames.get(i));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -428,8 +428,8 @@ public class MethodCallInfo {
|
||||
TypeInfo argType = arg.getResolvedType();
|
||||
if (argType != null && paramType != null) {
|
||||
if (!TypeChecker.isTypeCompatible(paramType, argType)) {
|
||||
setArgTypeError(i, "Expected " + paramType.getDisplayName() +
|
||||
" but got " + argType.getDisplayName());
|
||||
setArgTypeError(i, "Expected " + getTypeDisplayName(paramType) +
|
||||
" but got " + getTypeDisplayName(argType));
|
||||
}
|
||||
} else if (paramType == null) {
|
||||
setArgTypeError(i, "Parameter type of '" + para.getName() + "' is unresolved");
|
||||
@@ -439,6 +439,20 @@ public class MethodCallInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* in error "Expect T but got String", if T has a resolved bound aka "int" show it instead of T to avoid confusion.
|
||||
* So the error would be "Expect int but got String"
|
||||
*/
|
||||
public static String getTypeDisplayName(TypeInfo type) {
|
||||
if(type.isTypeParameter()) {
|
||||
TypeInfo bound = type.getBoundType();
|
||||
if (bound != null)
|
||||
return bound.getDisplayName();
|
||||
}
|
||||
|
||||
return type.getDisplayName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder("MethodCallInfo{");
|
||||
|
||||
@@ -163,10 +163,10 @@ public final class MethodInfo {
|
||||
if (reflectedReturn.isAssignableFrom(overrideClass)) {
|
||||
if (reflectedReturn != overrideClass) {
|
||||
returnType = overrideReturnType;
|
||||
System.out.println("[DtsJavaBridge] Overrode return type for "
|
||||
+ method.getDeclaringClass().getName() + "." + name
|
||||
+ "(" + method.getParameterCount() + ") from "
|
||||
+ reflectedReturn.getName() + " to " + overrideClass.getName());
|
||||
// System.out.println("[DtsJavaBridge] Overrode return type for "
|
||||
// + method.getDeclaringClass().getName() + "." + name
|
||||
// + "(" + method.getParameterCount() + ") from "
|
||||
// + reflectedReturn.getName() + " to " + overrideClass.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ public enum TokenType {
|
||||
ENUM_CONSTANT(0x55FFFF, 84, true, false), // enum constant values (blue, bold+italic) - like IntelliJ
|
||||
CLASS_DECL(0x00AAAA, 85), // class names in declarations
|
||||
IMPORTED_CLASS(0x00AAAA, 75), // imported class usages
|
||||
GENERIC_TYPE_PARAM(0x00FA9A, 76), // generic type parameters like T, E, K, V (light green)
|
||||
TYPE_DECL(0x00AAAA, 70), // package paths, type references
|
||||
|
||||
// Methods
|
||||
@@ -127,6 +128,8 @@ public enum TokenType {
|
||||
case INTERFACE_DECL:
|
||||
case GLOBAL_FIELD:
|
||||
return 'b'; // aqua
|
||||
case GENERIC_TYPE_PARAM:
|
||||
return 'a'; // green (distinct from class types)
|
||||
case CLASS_DECL:
|
||||
case IMPORTED_CLASS:
|
||||
case TYPE_DECL:
|
||||
|
||||
@@ -20,14 +20,14 @@ public final class GenericContext {
|
||||
/** Singleton context for types with no generic parameters. Used to avoid object allocation. */
|
||||
private static final GenericContext EMPTY = new GenericContext(new HashMap<>(), new HashMap<>());
|
||||
|
||||
/**
|
||||
/**
|
||||
* Map of type variable names to their applied type arguments.
|
||||
* For example, in List<String>, this contains E -> TypeInfo.STRING.
|
||||
* Applied bindings take precedence over bound fallbacks.
|
||||
*/
|
||||
private final Map<String, TypeInfo> appliedBindings;
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Map of type variable names to their declared upper bounds.
|
||||
* For example, in <T extends Entity>, this contains T -> TypeInfo(Entity).
|
||||
* Used as fallback when no applied argument exists.
|
||||
@@ -39,12 +39,53 @@ public final class GenericContext {
|
||||
this.boundFallbacks = boundFallbacks != null ? boundFallbacks : new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a GenericContext directly from declared type parameters and applied type arguments.
|
||||
*
|
||||
* Unlike {@link #forReceiver(TypeInfo)}, this does NOT introspect a TypeInfo, so it cannot
|
||||
* trigger recursive parameterization. Use this inside {@code parameterize()} implementations
|
||||
* to avoid the cycle: parameterize → forReceiver → substitute → parameterize.
|
||||
*
|
||||
* @param declaredParams the declared type parameters (e.g., [T, E])
|
||||
* @param appliedArgs the applied type arguments (e.g., [String, Integer])
|
||||
* @return a context mapping param names to applied args (with bound fallbacks for unmatched params)
|
||||
*/
|
||||
public static GenericContext fromBindings(List<TypeParamInfo> declaredParams, List<TypeInfo> appliedArgs) {
|
||||
if (declaredParams == null || declaredParams.isEmpty()) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
Map<String, TypeInfo> applied = new HashMap<>();
|
||||
if (appliedArgs != null) {
|
||||
int count = Math.min(declaredParams.size(), appliedArgs.size());
|
||||
for (int i = 0; i < count; i++) {
|
||||
TypeParamInfo declared = declaredParams.get(i);
|
||||
TypeInfo arg = appliedArgs.get(i);
|
||||
if (declared == null || declared.getName() == null || declared.getName().isEmpty() || arg == null) {
|
||||
continue;
|
||||
}
|
||||
applied.put(declared.getName(), arg);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, TypeInfo> bounds = new HashMap<>();
|
||||
for (TypeParamInfo declared : declaredParams) {
|
||||
if (declared == null) continue;
|
||||
String name = declared.getName();
|
||||
if (name == null || name.isEmpty()) continue;
|
||||
TypeInfo bound = declared.getBoundTypeInfo();
|
||||
bounds.put(name, (bound != null && bound.isResolved()) ? bound : TypeInfo.OBJECT);
|
||||
}
|
||||
|
||||
return new GenericContext(applied, bounds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a GenericContext for a receiver type.
|
||||
*
|
||||
*
|
||||
* Fast path: returns singleton EMPTY for non-generic types (no allocation overhead).
|
||||
* Slow path: builds maps from type parameters and applied arguments for generic types.
|
||||
*
|
||||
*
|
||||
* @param receiverType the type to extract generic bindings from (e.g., List<String>, DAO<T extends Entity>)
|
||||
* @return a context with applied bindings and bound fallbacks, or EMPTY singleton if receiverType is not generic
|
||||
*/
|
||||
@@ -85,9 +126,14 @@ public final class GenericContext {
|
||||
String name = declared.getName();
|
||||
if (name == null || name.isEmpty()) continue;
|
||||
TypeInfo bound = declared.getBoundTypeInfo();
|
||||
if (bound != null && bound.isResolved()) {
|
||||
bounds.put(name, bound);
|
||||
}
|
||||
TypeInfo effectiveBound = (bound != null && bound.isResolved()) ? bound : TypeInfo.OBJECT;
|
||||
|
||||
// TODO: Goatee not sure what this was for
|
||||
// List<TypeInfo> additionalBounds = declared.getAdditionalBoundTypes();
|
||||
// if (additionalBounds != null && !additionalBounds.isEmpty()) {
|
||||
// effectiveBound = IntersectionTypeInfo.of(effectiveBound, additionalBounds);
|
||||
// }
|
||||
bounds.put(name, effectiveBound);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,28 +142,28 @@ public final class GenericContext {
|
||||
|
||||
/**
|
||||
* Check if a type has generics that need substitution.
|
||||
*
|
||||
*
|
||||
* Returns true if:
|
||||
* - Type is parameterized (e.g., List<String>)
|
||||
* - Type's raw form differs from the type itself
|
||||
* - Type has declared type parameters
|
||||
*
|
||||
*
|
||||
* @param type the type to check
|
||||
* @return true if this type contains generic information that may need substitution
|
||||
*/
|
||||
public static boolean hasGenerics(TypeInfo type) {
|
||||
return type.isParameterized() ||
|
||||
type.getRawType() != type ||
|
||||
return type.isParameterized() ||
|
||||
type.getRawType() != type ||
|
||||
(type.getTypeParams() != null && !type.getTypeParams().isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a type variable to its bound or applied type.
|
||||
*
|
||||
*
|
||||
* Prefers applied bindings (e.g., E -> String in List<String>) over declared bounds.
|
||||
* Falls back to bounds (e.g., T -> Entity in <T extends Entity>) if no applied argument exists.
|
||||
* Returns null if the variable is not found in either map.
|
||||
*
|
||||
*
|
||||
* @param name the type variable name (e.g., "T", "E", "K")
|
||||
* @return the resolved TypeInfo, or null if variable not found
|
||||
*/
|
||||
@@ -136,12 +182,12 @@ public final class GenericContext {
|
||||
|
||||
/**
|
||||
* Substitute type variables in a TypeInfo recursively.
|
||||
*
|
||||
*
|
||||
* Handles:
|
||||
* - Direct type variables (unresolved types representing T, E, etc.)
|
||||
* - Parameterized types (recursively substitutes inside type arguments)
|
||||
* - Array types (substitutes the element type, preserves array dimensions)
|
||||
*
|
||||
*
|
||||
* @param type the type to substitute (may contain type variables)
|
||||
* @return the substituted type, or the original type if no substitutions apply
|
||||
*/
|
||||
@@ -150,9 +196,11 @@ public final class GenericContext {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Direct type variable substitution (unresolved types represent type variables like T).
|
||||
if (!type.isResolved()) {
|
||||
TypeInfo substitution = resolveTypeVariable(type.getSimpleName());
|
||||
// Direct type variable substitution.
|
||||
// Handles unresolved types (Java reflection path) and TypeInfo.typeParameter() (script-defined path).
|
||||
if (!type.isResolved() || type.isTypeParameter()) {
|
||||
String lookupKey = type.isTypeParameter() ? type.getTypeParameterName() : type.getSimpleName();
|
||||
TypeInfo substitution = resolveTypeVariable(lookupKey);
|
||||
if (substitution != null) {
|
||||
return substitution;
|
||||
}
|
||||
@@ -199,12 +247,12 @@ public final class GenericContext {
|
||||
|
||||
/**
|
||||
* Substitute type variables in a type string.
|
||||
*
|
||||
*
|
||||
* Attempts substitution in this order:
|
||||
* 1. Normalize the string (strip imports, pick union branch, remove nullable suffix, split arrays)
|
||||
* 2. Try direct type variable lookup (e.g., "T" -> resolved Entity)
|
||||
* 3. Fall back to full type resolution with substitution applied
|
||||
*
|
||||
*
|
||||
* @param typeString the type expression as a string (e.g., "T", "T[]", "List<T>")
|
||||
* @param resolver optional TypeResolver for fallback resolution; if null, returns null on failure
|
||||
* @return the substituted type, or null if resolution fails
|
||||
@@ -241,14 +289,14 @@ public final class GenericContext {
|
||||
|
||||
/**
|
||||
* Substitute type variables in a resolved type, with string fallback.
|
||||
*
|
||||
*
|
||||
* Two-phase approach:
|
||||
* 1. Try substituting the resolved type directly
|
||||
* 2. If that fails, attempt substitution via the raw string as fallback
|
||||
*
|
||||
*
|
||||
* This handles edge cases where the TypeInfo doesn't capture enough information
|
||||
* to do proper substitution (e.g., union types, complex generics).
|
||||
*
|
||||
*
|
||||
* @param resolvedType a TypeInfo that has already been resolved (may still contain type variables)
|
||||
* @param rawTypeString the original type string before resolution (for fallback)
|
||||
* @param resolver optional TypeResolver for string-based fallback resolution
|
||||
|
||||
@@ -2,6 +2,7 @@ package noppes.npcs.client.gui.util.script.interpreter.type;
|
||||
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.EnumConstantInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.field.FieldInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.js_parser.TypeParamInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodInfo;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.method.MethodSignature;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
|
||||
@@ -10,8 +11,10 @@ import java.lang.reflect.Method;
|
||||
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.Set;
|
||||
|
||||
/**
|
||||
* Represents a type defined within the script itself (not from Java classpath).
|
||||
@@ -37,6 +40,14 @@ public class ScriptTypeInfo extends TypeInfo {
|
||||
// Enum constants (for enum types only) - name -> EnumConstantInfo
|
||||
private final Map<String, EnumConstantInfo> enumConstants = new HashMap<>();
|
||||
|
||||
// Generic type parameters declared on this type (e.g., <E>, <K, V>, <T extends Entity>)
|
||||
private final List<TypeParamInfo> declaredTypeParams = new ArrayList<>();
|
||||
|
||||
// Recursion guard: tracks ScriptTypeInfo instances currently being parameterized on this thread
|
||||
// to break the cycle: parameterize → substitute → parameterize (self-referential types)
|
||||
private static final ThreadLocal<Set<ScriptTypeInfo>> PARAMETERIZING =
|
||||
ThreadLocal.withInitial(HashSet::new);
|
||||
|
||||
// Parent class reference (for inner class resolution)
|
||||
private ScriptTypeInfo outerClass;
|
||||
|
||||
@@ -101,6 +112,111 @@ public class ScriptTypeInfo extends TypeInfo {
|
||||
public ScriptTypeInfo getOuterClass() { return outerClass; }
|
||||
public List<ScriptTypeInfo> getInnerClasses() { return innerClasses; }
|
||||
|
||||
// ==================== GENERIC TYPE PARAMETERS ====================
|
||||
|
||||
public void addDeclaredTypeParam(TypeParamInfo param) {
|
||||
declaredTypeParams.add(param);
|
||||
}
|
||||
|
||||
public List<TypeParamInfo> getDeclaredTypeParams() {
|
||||
return declaredTypeParams;
|
||||
}
|
||||
|
||||
public TypeParamInfo getDeclaredTypeParam(String name) {
|
||||
for (TypeParamInfo param : declaredTypeParams) {
|
||||
if (param.getName().equals(name)) {
|
||||
return param;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean hasDeclaredTypeParams() {
|
||||
return !declaredTypeParams.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<TypeParamInfo> getTypeParams() {
|
||||
if (!declaredTypeParams.isEmpty()) {
|
||||
return declaredTypeParams;
|
||||
}
|
||||
return super.getTypeParams();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TypeParamInfo getTypeParam(String name) {
|
||||
TypeParamInfo param = getDeclaredTypeParam(name);
|
||||
if (param != null) {
|
||||
return param;
|
||||
}
|
||||
return super.getTypeParam(name);
|
||||
}
|
||||
|
||||
private static MethodInfo substituteMethod(MethodInfo m, GenericContext ctx) {
|
||||
TypeInfo retType = m.getReturnType();
|
||||
TypeInfo subRet = ctx.substitute(retType);
|
||||
List<FieldInfo> params = new ArrayList<>(m.getParameters());
|
||||
boolean changed = subRet != retType;
|
||||
for (int i = 0; i < params.size(); i++) {
|
||||
FieldInfo p = params.get(i);
|
||||
TypeInfo subP = ctx.substitute(p.getTypeInfo());
|
||||
if (subP != p.getTypeInfo()) {
|
||||
params.set(i, FieldInfo.reflectionParam(p.getName(), subP));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? MethodInfo.external(m.getName(), subRet, m.getContainingType(),
|
||||
params, m.getModifiers(), m.getDocumentation()) : m;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public TypeInfo parameterize(List<TypeInfo> typeArgs) {
|
||||
if (typeArgs == null || typeArgs.isEmpty()) return this;
|
||||
|
||||
Set<ScriptTypeInfo> active = PARAMETERIZING.get();
|
||||
if (!active.add(this)) {
|
||||
// Re-entrant call on the same raw type — fall back to shallow parameterization
|
||||
// (no method/field substitution) to break the infinite recursion.
|
||||
return super.parameterize(typeArgs);
|
||||
}
|
||||
|
||||
try {
|
||||
ScriptTypeInfo result = new ScriptTypeInfo(getSimpleName(), getFullName(), getKind(),
|
||||
declarationOffset, bodyStart, bodyEnd, modifiers);
|
||||
result.setRawType(this);
|
||||
result.setAppliedTypeArgs(typeArgs);
|
||||
result.superClass = this.superClass;
|
||||
result.superClassName = this.superClassName;
|
||||
result.implementedInterfaces.addAll(this.implementedInterfaces);
|
||||
result.implementedInterfaceNames.addAll(this.implementedInterfaceNames);
|
||||
result.declaredTypeParams.addAll(this.declaredTypeParams);
|
||||
result.outerClass = this.outerClass;
|
||||
// Use fromBindings instead of forReceiver to avoid infinite recursion:
|
||||
// forReceiver(result) → substitute() → parameterize() → forReceiver() → ...
|
||||
GenericContext ctx = GenericContext.fromBindings(this.declaredTypeParams, typeArgs);
|
||||
|
||||
// Parameterize methods, constructors, and fields with the generic context of this type.
|
||||
for (Map.Entry<String, List<MethodInfo>> entry : this.methods.entrySet()) {
|
||||
List<MethodInfo> substituted = new ArrayList<>();
|
||||
for (MethodInfo m : entry.getValue()) substituted.add(substituteMethod(m, ctx));
|
||||
result.methods.put(entry.getKey(), substituted);
|
||||
}
|
||||
for (MethodInfo ctor : this.constructors) {
|
||||
result.constructors.add(substituteMethod(ctor, ctx));
|
||||
}
|
||||
for (Map.Entry<String, FieldInfo> entry : this.fields.entrySet()) {
|
||||
FieldInfo f = entry.getValue();
|
||||
TypeInfo subType = ctx.substitute(f.getTypeInfo());
|
||||
result.fields.put(entry.getKey(), subType != f.getTypeInfo()
|
||||
? FieldInfo.external(f.getName(), subType, null, f.getModifiers()) : f);
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
active.remove(this);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== INHERITANCE ====================
|
||||
|
||||
/**
|
||||
@@ -884,20 +1000,18 @@ public class ScriptTypeInfo extends TypeInfo {
|
||||
// If no constructors defined in script type, it has an implicit default constructor
|
||||
// Check if parent has a no-arg constructor
|
||||
if (!hasConstructors()) {
|
||||
boolean parentHasNoArg = false;
|
||||
|
||||
if (superClass instanceof ScriptTypeInfo) {
|
||||
ScriptTypeInfo parentScript = (ScriptTypeInfo) superClass;
|
||||
if (!parentScript.hasConstructors() || parentScript.findConstructor(0) != null) {
|
||||
parentHasNoArg = true;
|
||||
if (!parentScript.isInterface() && (!parentScript.hasConstructors() || parentScript.findConstructor(0) != null)) {
|
||||
addConstructorMismatchError(superClass, superClass.getSimpleName());
|
||||
}
|
||||
} else {
|
||||
Class<?> javaClass = superClass.getJavaClass();
|
||||
if (javaClass != null) {
|
||||
if (javaClass != null && !javaClass.isInterface()) {
|
||||
try {
|
||||
for (java.lang.reflect.Constructor<?> ctor : javaClass.getConstructors()) {
|
||||
if (ctor.getParameterCount() == 0) {
|
||||
parentHasNoArg = true;
|
||||
addConstructorMismatchError(superClass, superClass.getSimpleName());
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -907,9 +1021,6 @@ public class ScriptTypeInfo extends TypeInfo {
|
||||
}
|
||||
}
|
||||
|
||||
if (!parentHasNoArg) {
|
||||
addConstructorMismatchError(superClass, superClass.getSimpleName());
|
||||
}
|
||||
}
|
||||
// If script type has constructors, we'd need to check super() calls - that's more complex
|
||||
// For now, we just validate the implicit default constructor case
|
||||
|
||||
@@ -2,6 +2,8 @@ package noppes.npcs.client.gui.util.script.interpreter.type;
|
||||
|
||||
import noppes.npcs.client.gui.util.script.interpreter.js_parser.JSTypeInfo;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -33,6 +35,9 @@ public final class TypeChecker {
|
||||
if (expected == null) return true; // void can accept anything (shouldn't happen)
|
||||
if (actual == null) return true; // Can't verify, assume compatible
|
||||
|
||||
// Exact match by reference equality
|
||||
if(expected.equals(actual)) return true;
|
||||
|
||||
// Handle array types: compatible if element types are compatible
|
||||
if (expected.isArray() && actual.isArray()) {
|
||||
TypeInfo expectedElement = expected.getElementType();
|
||||
@@ -78,13 +83,6 @@ public final class TypeChecker {
|
||||
|
||||
if (expectedName == null || actualName == null) return true;
|
||||
|
||||
// Exact match by simple name
|
||||
if (expectedName.equals(actualName)) return true;
|
||||
|
||||
// Exact match by full name
|
||||
if (expected.getFullName() != null && actual.getFullName() != null) {
|
||||
if (expected.getFullName().equals(actual.getFullName())) return true;
|
||||
}
|
||||
|
||||
// Primitive widening conversions
|
||||
if ("number".equals(expectedName) && isNumericType(actualName)) {
|
||||
@@ -104,7 +102,24 @@ public final class TypeChecker {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Same-name match: handles ScriptTypeInfo, non-Java types, and same-class Java types.
|
||||
// Must run before isAssignableFrom so type arg checking isn't skipped for same-class pairs.
|
||||
if (expected.getFullName().equals(actual.getFullName())) {
|
||||
if (expected.isParameterized() && actual.isParameterized()) {
|
||||
return areTypeArgumentsCompatible(expected, actual);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ScriptTypeInfo inheritance: actual is a script-defined type that may extend/implement expected.
|
||||
// ScriptTypeInfo.getJavaClass() returns null, so the Java isAssignableFrom gate below won't fire.
|
||||
if (actual instanceof ScriptTypeInfo) {
|
||||
if (isScriptTypeAssignableTo((ScriptTypeInfo) actual, expected)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Object type compatibility (check inheritance)
|
||||
if (expected.getJavaClass() != null && actual.getJavaClass() != null) {
|
||||
Class<?> expectedClass = expected.getJavaClass();
|
||||
@@ -160,6 +175,85 @@ public final class TypeChecker {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check assignability for ScriptTypeInfo by iteratively walking the extends/implements chain.
|
||||
* Handles both direct and indirect inheritance (A extends B extends C implements D).
|
||||
*/
|
||||
private static boolean isScriptTypeAssignableTo(ScriptTypeInfo actual, TypeInfo expected) {
|
||||
String expectedFull = expected.getFullName();
|
||||
String expectedSimple = expected.getSimpleName();
|
||||
|
||||
Deque<TypeInfo> worklist = new ArrayDeque<>();
|
||||
worklist.add(actual);
|
||||
|
||||
while (!worklist.isEmpty()) {
|
||||
TypeInfo current = worklist.poll();
|
||||
if (current == null || !current.isResolved()) continue;
|
||||
|
||||
String currentFull = current.getFullName();
|
||||
if (currentFull != null) {
|
||||
if (expectedFull != null && expectedFull.equals(currentFull)) return true;
|
||||
if (expectedSimple != null && expectedSimple.equals(current.getSimpleName())) return true;
|
||||
}
|
||||
|
||||
if (current instanceof ScriptTypeInfo) {
|
||||
ScriptTypeInfo scriptCurrent = (ScriptTypeInfo) current;
|
||||
TypeInfo superClass = scriptCurrent.getSuperClass();
|
||||
if (superClass != null) {
|
||||
worklist.add(superClass);
|
||||
}
|
||||
for (TypeInfo iface : scriptCurrent.getImplementedInterfaces()) {
|
||||
worklist.add(iface);
|
||||
}
|
||||
} else if (current.getJavaClass() != null && expected.getJavaClass() != null) {
|
||||
if (expected.getJavaClass().isAssignableFrom(current.getJavaClass())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean areTypeArgumentsCompatible(TypeInfo expected, TypeInfo actual) {
|
||||
java.util.List<TypeInfo> expectedArgs = expected.getAppliedTypeArgs();
|
||||
java.util.List<TypeInfo> actualArgs = actual.getAppliedTypeArgs();
|
||||
|
||||
// Actual has no type args — it's a raw type being assigned to a parameterized type.
|
||||
// In Java this is always valid (unchecked warning, not an error).
|
||||
if (actualArgs.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If all of actual's type args are unresolved type parameters (e.g., Box<T>
|
||||
// from diamond "new Box<>()"), treat as raw/inferred — always compatible.
|
||||
boolean allActualAreTypeParams = true;
|
||||
for (TypeInfo actualArg : actualArgs) {
|
||||
if (!actualArg.isTypeParameter()) {
|
||||
allActualAreTypeParams = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (allActualAreTypeParams) {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (int i = 0; i < expectedArgs.size(); i++) {
|
||||
TypeInfo expectedArg = expectedArgs.get(i);
|
||||
TypeInfo actualArg = actualArgs.get(i);
|
||||
|
||||
if (expectedArg.isTypeParameter() || actualArg.isTypeParameter()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isTypeCompatible(expectedArg, actualArg) && !isTypeCompatible(actualArg, expectedArg)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the type is a numeric type (including wrappers).
|
||||
*/
|
||||
|
||||
@@ -14,11 +14,7 @@ import noppes.npcs.client.gui.util.script.interpreter.method.MethodSignature;
|
||||
import noppes.npcs.client.gui.util.script.interpreter.token.TokenType;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
@@ -86,6 +82,8 @@ public class TypeInfo {
|
||||
|
||||
private boolean isPrimitive; // Whether this is a primitive type (e.g., int, boolean)
|
||||
private boolean isObjectLiteral;
|
||||
private String typeParameterName; // Non-null if this TypeInfo represents a type parameter (e.g., "T")
|
||||
private TypeInfo boundType; // For type parameters with bounds, stores the bound for resolution
|
||||
|
||||
// JavaScript/TypeScript type info (for types from .d.ts files)
|
||||
private final JSTypeInfo jsTypeInfo; // The JS type info (null if Java type)
|
||||
@@ -95,11 +93,11 @@ public class TypeInfo {
|
||||
|
||||
// Applied type arguments (concrete types provided for generics, e.g., <String, Integer> in Map<String, Integer>)
|
||||
// These are TypeInfo instances that can themselves be parameterized for nested generics
|
||||
private final List<TypeInfo> appliedTypeArgs = new ArrayList<>();
|
||||
private List<TypeInfo> appliedTypeArgs = new ArrayList<>();
|
||||
|
||||
// For parameterized types, the raw/base type (e.g., List for List<String>)
|
||||
// Null for non-parameterized types
|
||||
private final TypeInfo rawType;
|
||||
private TypeInfo rawType;
|
||||
|
||||
// For array types, the element type (e.g., IItemStack for IItemStack[])
|
||||
// Null for non-array types
|
||||
@@ -178,6 +176,42 @@ public class TypeInfo {
|
||||
return new TypeInfo(simpleName, fullPath, pkg, Kind.UNKNOWN, null, false, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a TypeInfo representing an unbounded type parameter (e.g., {@code T} in {@code class Box<T>}).
|
||||
* Uses Object.class for member lookup (erasure semantics) but displays as the parameter name.
|
||||
*/
|
||||
public static TypeInfo typeParameter(String paramName) {
|
||||
TypeInfo ti = new TypeInfo(paramName, paramName, "", Kind.CLASS, Object.class, true, null);
|
||||
ti.typeParameterName = paramName;
|
||||
return ti;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a TypeInfo representing a bounded type parameter (e.g., {@code T extends Entity}).
|
||||
* Keeps the type parameter's own identity (paramName as simpleName/fullName) but stores the
|
||||
* bound separately for display. Uses the bound's javaClass/kind for member resolution (erasure semantics).
|
||||
*/
|
||||
public static TypeInfo typeParameter(String paramName, TypeInfo boundType) {
|
||||
Class<?> javaClass = (boundType != null && boundType.javaClass != null) ? boundType.javaClass : Object.class;
|
||||
Kind kind = (boundType != null) ? boundType.kind : Kind.CLASS;
|
||||
TypeInfo ti = new TypeInfo(paramName, paramName, "", kind, javaClass, true, null);
|
||||
ti.typeParameterName = paramName;
|
||||
ti.boundType = boundType;
|
||||
return ti;
|
||||
}
|
||||
|
||||
public boolean isTypeParameter() {
|
||||
return typeParameterName != null;
|
||||
}
|
||||
|
||||
public String getTypeParameterName() {
|
||||
return typeParameterName;
|
||||
}
|
||||
|
||||
public TypeInfo getBoundType() {
|
||||
return boundType;
|
||||
}
|
||||
|
||||
public static TypeInfo fromClass(Class<?> clazz) {
|
||||
if (clazz == null) return null;
|
||||
|
||||
@@ -277,12 +311,14 @@ public class TypeInfo {
|
||||
}
|
||||
|
||||
if (type instanceof TypeVariable<?>) {
|
||||
// Type variable like T, E, K, V
|
||||
TypeVariable<?> typeVar = (TypeVariable<?>) type;
|
||||
String varName = typeVar.getName();
|
||||
// Create an unresolved type representing the type variable
|
||||
// The substitution system will handle replacing this with the actual type
|
||||
return TypeInfo.unresolved(varName, varName);
|
||||
// Check for bounds - if bounded, create typeParameter with bound
|
||||
Type[] bounds = typeVar.getBounds();
|
||||
if (bounds != null && bounds.length > 0 && bounds[0] != Object.class) {
|
||||
return TypeInfo.typeParameter(varName, fromGenericType(bounds[0]));
|
||||
}
|
||||
return TypeInfo.typeParameter(varName);
|
||||
}
|
||||
|
||||
if (type instanceof WildcardType) {
|
||||
@@ -454,14 +490,18 @@ public class TypeInfo {
|
||||
// Fallback to Object array if we can't create the specific array type
|
||||
}
|
||||
}
|
||||
|
||||
TypeInfo arr = new TypeInfo(simpleName, fullName, pkg, elementType.kind, arrayClass, true, null, null, null, null, elementType);
|
||||
TypeInfo arr = new TypeInfo(simpleName, fullName, pkg, elementType.kind, arrayClass, elementType.isResolved(),
|
||||
null, null, null, null, elementType);
|
||||
arr.setPrimitive(elementType.isPrimitive());
|
||||
arr.syntheticFields.add(FieldInfo.external("length", TypeInfo.fromPrimitive("int"), null,
|
||||
Modifier.PUBLIC | Modifier.FINAL));
|
||||
arr.syntheticMethods.add(MethodInfo.external("clone", arr, null,
|
||||
Collections.emptyList(), Modifier.PUBLIC, null));
|
||||
return arr;
|
||||
|
||||
arr.typeParameterName = elementType.typeParameterName;
|
||||
if (elementType.boundType != null)
|
||||
arr.boundType = arrayOf(elementType.boundType);
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -541,6 +581,14 @@ public class TypeInfo {
|
||||
public List<TypeInfo> getAppliedTypeArgs() {
|
||||
return appliedTypeArgs;
|
||||
}
|
||||
|
||||
protected void setRawType(TypeInfo rawType) {
|
||||
this.rawType = rawType;
|
||||
}
|
||||
|
||||
protected void setAppliedTypeArgs(List<TypeInfo> args) {
|
||||
this.appliedTypeArgs = new ArrayList<>(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a parameterized version of this type with the given type arguments.
|
||||
@@ -645,6 +693,8 @@ public class TypeInfo {
|
||||
public TokenType getTokenType() {
|
||||
if (!resolved)
|
||||
return TokenType.UNDEFINED_VAR;
|
||||
if (isTypeParameter())
|
||||
return TokenType.GENERIC_TYPE_PARAM;
|
||||
if(isPrimitive())
|
||||
return TokenType.KEYWORD;
|
||||
|
||||
@@ -1215,19 +1265,6 @@ public class TypeInfo {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a type parameter to its bound TypeInfo.
|
||||
* For example, if this type has "T extends EntityPlayerMP", resolveTypeParamToTypeInfo("T") returns the TypeInfo for EntityPlayerMP.
|
||||
* If no type parameter is found with that name, returns null.
|
||||
*/
|
||||
public TypeInfo resolveTypeParamToTypeInfo(String typeName) {
|
||||
TypeParamInfo param = getTypeParam(typeName);
|
||||
if (param != null) {
|
||||
return param.getBoundTypeInfo();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TypeInfo{" + fullName + ", " + kind + ", resolved=" + resolved + "}";
|
||||
@@ -1236,13 +1273,36 @@ public class TypeInfo {
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
TypeInfo typeInfo = (TypeInfo) o;
|
||||
return fullName.equals(typeInfo.fullName);
|
||||
if (!(o instanceof TypeInfo))
|
||||
return false;
|
||||
TypeInfo other = (TypeInfo) o;
|
||||
|
||||
if (!fullName.equals(other.fullName))
|
||||
return false;
|
||||
|
||||
if (typeParameterName != null || other.typeParameterName != null) {
|
||||
if (!Objects.equals(typeParameterName, other.typeParameterName))
|
||||
return false;
|
||||
if (!Objects.equals(boundType, other.boundType))
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!appliedTypeArgs.equals(other.appliedTypeArgs))
|
||||
return false;
|
||||
|
||||
if (!Objects.equals(elementType, other.elementType))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return fullName.hashCode();
|
||||
int result = fullName.hashCode();
|
||||
if (typeParameterName != null)
|
||||
result = 31 * result + typeParameterName.hashCode();
|
||||
if (elementType != null)
|
||||
result = 31 * result + elementType.hashCode();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -92,9 +92,14 @@ public class TypeSubstitutor {
|
||||
|
||||
String typeName = type.getSimpleName();
|
||||
|
||||
// Check if this type is itself a type variable
|
||||
if (!type.isResolved()) {
|
||||
TypeInfo substitution = bindings.get(typeName);
|
||||
// Check if this type is itself a type variable.
|
||||
// Two cases:
|
||||
// 1. Unresolved TypeInfo (Java reflection path: TypeInfo.fromGenericType creates these for T, E, K, V)
|
||||
// 2. TypeInfo.typeParameter() (script-defined path: resolved but tagged as a type parameter)
|
||||
// For tagged type parameters, use getTypeParameterName() as the lookup key.
|
||||
if (!type.isResolved() || type.isTypeParameter()) {
|
||||
String lookupKey = type.isTypeParameter() ? type.getTypeParameterName() : typeName;
|
||||
TypeInfo substitution = bindings.get(lookupKey);
|
||||
if (substitution != null) {
|
||||
return substitution;
|
||||
}
|
||||
@@ -138,60 +143,4 @@ public class TypeSubstitutor {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitute type variables in a type string using the given bindings.
|
||||
* Used when we have a raw type string (like "T" or "List<T>") that needs substitution.
|
||||
*
|
||||
* @param typeString The raw type string
|
||||
* @param bindings The map from type variable names to concrete types
|
||||
* @param resolver The type resolver to use for parsing
|
||||
* @return The substituted TypeInfo
|
||||
*/
|
||||
public static TypeInfo substituteString(String typeString, Map<String, TypeInfo> bindings, TypeResolver resolver) {
|
||||
if (typeString == null || typeString.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// First check if the whole string is a type variable
|
||||
String trimmed = TypeStringNormalizer.stripImportTypeSyntax(typeString);
|
||||
trimmed = TypeStringNormalizer.pickPreferredUnionBranch(trimmed);
|
||||
trimmed = TypeStringNormalizer.stripNullableSuffix(trimmed);
|
||||
|
||||
TypeStringNormalizer.ArraySplit arraySplit = TypeStringNormalizer.splitArraySuffixes(trimmed);
|
||||
String baseName = arraySplit.base;
|
||||
int arrayDims = arraySplit.dimensions;
|
||||
|
||||
// Strip generic args to check the base name
|
||||
String bareBaseName = GenericTypeParser.stripGenerics(baseName);
|
||||
|
||||
// If bare base name is a type variable, substitute
|
||||
TypeInfo directSubstitution = bindings.get(bareBaseName);
|
||||
if (directSubstitution != null) {
|
||||
// It's a type variable, return the substitution
|
||||
TypeInfo result = directSubstitution;
|
||||
for (int i = 0; i < arrayDims; i++) {
|
||||
result = TypeInfo.arrayOf(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Parse and resolve the type, then substitute within it
|
||||
TypeInfo resolved = resolver.resolveJSType(typeString);
|
||||
return substitute(resolved, bindings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the return type for a method on a parameterized receiver, with type variable substitution.
|
||||
*
|
||||
* @param rawReturnType The method's raw return type (may contain type variables)
|
||||
* @param rawReturnTypeString The method's raw return type as a string (for unresolved types)
|
||||
* @param receiverType The parameterized receiver type
|
||||
* @param resolver The type resolver
|
||||
* @return The substituted return type
|
||||
*/
|
||||
public static TypeInfo getSubstitutedReturnType(TypeInfo rawReturnType, String rawReturnTypeString,
|
||||
TypeInfo receiverType, TypeResolver resolver) {
|
||||
GenericContext ctx = GenericContext.forReceiver(receiverType);
|
||||
return ctx.substituteType(rawReturnType, rawReturnTypeString, resolver);
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,15 @@ public class KeyPresetManager {
|
||||
try {
|
||||
File dir = getDir();
|
||||
File file = new File(dir, fileName + ".json");
|
||||
if (!file.exists())
|
||||
if (!file.exists()) {
|
||||
// First run: initialize all keys to their default states if not already set
|
||||
for (KeyPreset key : keys) {
|
||||
if (!key.defaultState.hasState()) {
|
||||
key.currentState.readFrom(key.defaultState);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
NBTTagCompound compound = NBTJsonUtil.LoadFile(file);
|
||||
for (KeyPreset key : keys)
|
||||
|
||||
@@ -544,65 +544,80 @@ public class RenderNPCInterface extends RenderLiving {
|
||||
|
||||
@Override
|
||||
public ResourceLocation getEntityTexture(Entity entity) {
|
||||
|
||||
EntityNPCInterface npc = (EntityNPCInterface) entity;
|
||||
if (npc.textureLocation == null) {
|
||||
if (npc.display.skinType == 0) {
|
||||
|
||||
// Early exit if texture already resolved
|
||||
if (npc.textureLocation != null) {
|
||||
return npc.textureLocation;
|
||||
}
|
||||
|
||||
// SkinType 0: custom texture or default
|
||||
if (npc.display.skinType == 0) {
|
||||
if (npc.display.texture.isEmpty()) {
|
||||
return npc.textureLocation = fallBackSkin(npc);
|
||||
}
|
||||
|
||||
try {
|
||||
if (npc instanceof EntityCustomNpc && ((EntityCustomNpc) npc).modelData.entityClass == null) {
|
||||
if (!(npc.display.texture).isEmpty()) {
|
||||
try {
|
||||
npc.textureLocation = adjustLocalTexture(npc, new ResourceLocation(npc.display.texture));
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
npc.textureLocation = adjustLocalTexture(npc, new ResourceLocation(npc.display.texture));
|
||||
} else {
|
||||
npc.textureLocation = new ResourceLocation(npc.display.texture);
|
||||
ResourceLocation resLoc = new ResourceLocation(npc.display.texture);
|
||||
Minecraft.getMinecraft().getResourceManager().getResource(resLoc);
|
||||
npc.textureLocation = resLoc;
|
||||
}
|
||||
} else if (npc.display.skinType == 1 && npc.display.playerProfile != null) {
|
||||
Minecraft minecraft = Minecraft.getMinecraft();
|
||||
Map map = minecraft.func_152342_ad().func_152788_a(npc.display.playerProfile);
|
||||
if (map.containsKey(Type.SKIN)) {
|
||||
npc.textureLocation = minecraft.func_152342_ad().func_152792_a((MinecraftProfileTexture) map.get(Type.SKIN), Type.SKIN);
|
||||
}
|
||||
LastTextureTick = 0;
|
||||
} else if (npc.display.skinType == 2 || npc.display.skinType == 3) {
|
||||
ResourceLocation location = new ResourceLocation("skins/" + (npc.display.skinType + npc.display.url).hashCode());
|
||||
// If URL Empty Steve
|
||||
if (npc.display.url.isEmpty()) {
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
// If URL Cached then grab it
|
||||
else if (ClientCacheHandler.isCachedNPC(location)) {
|
||||
try {
|
||||
ResourceLocation loc = ClientCacheHandler.getNPCTexture(npc.display.url, npc.display.skinType == 3, location).getLocation();
|
||||
if (loc != null) {
|
||||
npc.textureLocation = loc;
|
||||
} else {
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
// For New URL Requests do not spam it
|
||||
else if (LastTextureTick < 5) { //fixes request flood somewhat
|
||||
return fallBackSkin(npc);
|
||||
} else {
|
||||
try {
|
||||
ResourceLocation loc = ClientCacheHandler.getNPCTexture(npc.display.url, npc.display.skinType == 3, location).getLocation();
|
||||
if (loc != null) {
|
||||
npc.textureLocation = loc;
|
||||
} else {
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
LastTextureTick = 0;
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} catch (IOException ignored) {
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
}
|
||||
return npc.textureLocation;
|
||||
|
||||
// SkinType 1: player profile skin
|
||||
else if (npc.display.skinType == 1 && npc.display.playerProfile != null) {
|
||||
final Minecraft minecraft = Minecraft.getMinecraft();
|
||||
Map map = minecraft.func_152342_ad().func_152788_a(npc.display.playerProfile);
|
||||
if (map.containsKey(Type.SKIN)) {
|
||||
npc.textureLocation = minecraft.func_152342_ad()
|
||||
.func_152792_a((MinecraftProfileTexture) map.get(Type.SKIN), Type.SKIN);
|
||||
}
|
||||
LastTextureTick = 0;
|
||||
}
|
||||
|
||||
// SkinType 2 / 3: load from URL
|
||||
else if (npc.display.skinType == 2 || npc.display.skinType == 3) {
|
||||
if (npc.display.url.isEmpty()) { // If URL is empty → fallback
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
|
||||
ResourceLocation location = new ResourceLocation("skins/" + (npc.display.skinType + npc.display.url).hashCode());
|
||||
|
||||
try {
|
||||
if (ClientCacheHandler.isCachedNPC(location)) { // If URL is cached
|
||||
ResourceLocation loc = ClientCacheHandler
|
||||
.getNPCTexture(npc.display.url, npc.display.skinType == 3, location)
|
||||
.getLocation();
|
||||
if (loc == null) return fallBackSkin(npc);
|
||||
npc.textureLocation = loc;
|
||||
} else if (LastTextureTick >= 5) { // Prevent request flooding
|
||||
ResourceLocation loc = ClientCacheHandler
|
||||
.getNPCTexture(npc.display.url, npc.display.skinType == 3, location)
|
||||
.getLocation();
|
||||
if (loc == null) return fallBackSkin(npc);
|
||||
npc.textureLocation = loc;
|
||||
LastTextureTick = 0;
|
||||
} else {
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: if no valid skin type matched
|
||||
else {
|
||||
return fallBackSkin(npc);
|
||||
}
|
||||
|
||||
// Final safety net
|
||||
return npc.textureLocation == null ? fallBackSkin(npc) : npc.textureLocation;
|
||||
}
|
||||
|
||||
private ResourceLocation adjustLocalTexture(EntityNPCInterface npc, ResourceLocation location) throws IOException {
|
||||
|
||||
@@ -87,10 +87,10 @@ public class ConfigClient {
|
||||
public static float QuestOverlayX = 0;
|
||||
|
||||
public static Property QuestOverlayYProperty;
|
||||
public static float QuestOverlayY = 31;
|
||||
public static float QuestOverlayY = 14;
|
||||
|
||||
public static Property QuestOverlayScaleProperty;
|
||||
public static int QuestOverlayScale = 223;
|
||||
public static int QuestOverlayScale = 246;
|
||||
|
||||
public static Property QuestOverlayTextAlignProperty;
|
||||
public static int QuestOverlayTextAlign = 0; // 0: Left, 1: Center, 2: Right
|
||||
@@ -99,35 +99,35 @@ public class ConfigClient {
|
||||
public static boolean CompassEnabled = true;
|
||||
|
||||
public static Property CompassOverlayXProperty;
|
||||
public static float CompassOverlayX = 37;
|
||||
public static float CompassOverlayX = 36;
|
||||
|
||||
public static Property CompassOverlayYProperty;
|
||||
public static float CompassOverlayY = 0;
|
||||
|
||||
public static Property CompassOverlayScaleProperty;
|
||||
public static int CompassOverlayScale = 276;
|
||||
public static int CompassOverlayScale = 344;
|
||||
|
||||
public static Property CompassOverlayWidthProperty;
|
||||
public static int CompassOverlayWidth = 200;
|
||||
public static int CompassOverlayWidth = 158;
|
||||
|
||||
// Ability Hotbar HUD
|
||||
public static Property AbilityHotbarEnabledProperty;
|
||||
public static boolean AbilityHotbarEnabled = true;
|
||||
|
||||
public static Property AbilityHotbarXProperty;
|
||||
public static float AbilityHotbarX = 3;
|
||||
public static float AbilityHotbarX = 0;
|
||||
|
||||
public static Property AbilityHotbarYProperty;
|
||||
public static float AbilityHotbarY = 50;
|
||||
public static float AbilityHotbarY = 43;
|
||||
|
||||
public static Property AbilityHotbarScaleProperty;
|
||||
public static int AbilityHotbarScale = 100;
|
||||
public static int AbilityHotbarScale = 227;
|
||||
|
||||
public static Property AbilityHotbarHorizontalProperty;
|
||||
public static boolean AbilityHotbarHorizontal = false;
|
||||
|
||||
public static Property AbilityHotbarAltTextureProperty;
|
||||
public static boolean AbilityHotbarAltTexture = false;
|
||||
public static boolean AbilityHotbarAltTexture = true;
|
||||
|
||||
// 1=Above(H)/Left(V), 2=Below(H)/Right(V)
|
||||
public static Property AbilityHotbarTextPositionProperty;
|
||||
@@ -179,11 +179,11 @@ public class ConfigClient {
|
||||
QuestOverlayXProperty = config.get(HUD, "Quest Hud X", 0.0, "X position of the quest overlay.");
|
||||
QuestOverlayX = (float) QuestOverlayXProperty.getDouble(0);
|
||||
|
||||
QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 31.0, "Y position of the quest overlay.");
|
||||
QuestOverlayY = (float) QuestOverlayYProperty.getDouble(31);
|
||||
QuestOverlayYProperty = config.get(HUD, "Quest Hud Y", 14.0, "Y position of the quest overlay.");
|
||||
QuestOverlayY = (float) QuestOverlayYProperty.getDouble(14);
|
||||
|
||||
QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 223, "Scale percentage of the quest overlay.");
|
||||
QuestOverlayScale = QuestOverlayScaleProperty.getInt(223);
|
||||
QuestOverlayScaleProperty = config.get(HUD, "Quest Hud Scale", 246, "Scale percentage of the quest overlay.");
|
||||
QuestOverlayScale = QuestOverlayScaleProperty.getInt(246);
|
||||
|
||||
QuestOverlayTextAlignProperty = config.get(HUD, "Quest Hud Text Alignment", 0, "Text alignment in quest overlay (0: Left, 1: Center, 2: Right).");
|
||||
QuestOverlayTextAlign = QuestOverlayTextAlignProperty.getInt(0);
|
||||
@@ -200,7 +200,7 @@ public class ConfigClient {
|
||||
CompassOverlayXProperty = config.get(
|
||||
HUD,
|
||||
"Compass Hud X",
|
||||
37.0,
|
||||
36.0,
|
||||
"Horizontal position of compass overlay (0-100 percentage)"
|
||||
);
|
||||
CompassOverlayX = (float) CompassOverlayXProperty.getDouble();
|
||||
@@ -216,19 +216,19 @@ public class ConfigClient {
|
||||
CompassOverlayScaleProperty = config.get(
|
||||
HUD,
|
||||
"Compass Hud Scale",
|
||||
276,
|
||||
344,
|
||||
"Scale percentage of compass overlay",
|
||||
50,
|
||||
300
|
||||
500
|
||||
);
|
||||
CompassOverlayScale = CompassOverlayScaleProperty.getInt();
|
||||
|
||||
CompassOverlayWidthProperty = config.get(
|
||||
HUD,
|
||||
"Compass Hud Width",
|
||||
200,
|
||||
158,
|
||||
"Base width of compass bar in pixels",
|
||||
100,
|
||||
50,
|
||||
1000
|
||||
);
|
||||
CompassOverlayWidth = CompassOverlayWidthProperty.getInt();
|
||||
@@ -237,19 +237,19 @@ public class ConfigClient {
|
||||
AbilityHotbarEnabledProperty = config.get(HUD, "Ability Hotbar Enabled", true, "Enable Ability Hotbar HUD Component");
|
||||
AbilityHotbarEnabled = AbilityHotbarEnabledProperty.getBoolean();
|
||||
|
||||
AbilityHotbarXProperty = config.get(HUD, "Ability Hotbar X", 3.0, "Horizontal position (0-100 percentage)");
|
||||
AbilityHotbarXProperty = config.get(HUD, "Ability Hotbar X", 0.0, "Horizontal position (0-100 percentage)");
|
||||
AbilityHotbarX = (float) AbilityHotbarXProperty.getDouble();
|
||||
|
||||
AbilityHotbarYProperty = config.get(HUD, "Ability Hotbar Y", 50.0, "Vertical position (0-100 percentage)");
|
||||
AbilityHotbarYProperty = config.get(HUD, "Ability Hotbar Y", 43.0, "Vertical position (0-100 percentage)");
|
||||
AbilityHotbarY = (float) AbilityHotbarYProperty.getDouble();
|
||||
|
||||
AbilityHotbarScaleProperty = config.get(HUD, "Ability Hotbar Scale", 100, "Scale percentage", 50, 300);
|
||||
AbilityHotbarScaleProperty = config.get(HUD, "Ability Hotbar Scale", 227, "Scale percentage", 50, 500);
|
||||
AbilityHotbarScale = AbilityHotbarScaleProperty.getInt();
|
||||
|
||||
AbilityHotbarHorizontalProperty = config.get(HUD, "Ability Hotbar Horizontal", false, "Display horizontally instead of vertically");
|
||||
AbilityHotbarHorizontal = AbilityHotbarHorizontalProperty.getBoolean();
|
||||
|
||||
AbilityHotbarAltTextureProperty = config.get(HUD, "Ability Hotbar Alt Texture", false, "Use rounded square instead of circle slots");
|
||||
AbilityHotbarAltTextureProperty = config.get(HUD, "Ability Hotbar Alt Texture", true, "Use rounded square instead of circle slots");
|
||||
AbilityHotbarAltTexture = AbilityHotbarAltTextureProperty.getBoolean();
|
||||
|
||||
AbilityHotbarTextPositionProperty = config.get(HUD, "Ability Hotbar Text Position", 2, "Text label position (1=Above/Left, 2=Below/Right)");
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package noppes.npcs.controllers;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class APIRegistry {
|
||||
public static final APIRegistry Instance = new APIRegistry();
|
||||
|
||||
private final LinkedHashMap<String, String> entries = new LinkedHashMap<>();
|
||||
|
||||
public void register(String name, String url) {
|
||||
entries.put(name, url);
|
||||
}
|
||||
|
||||
public void unregister(String name) {
|
||||
entries.remove(name);
|
||||
}
|
||||
|
||||
public LinkedHashMap<String, String> getEntries() {
|
||||
return entries;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return entries.size();
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,8 @@ public class AnimationController implements IAnimationHandler {
|
||||
|
||||
// Built-in animations loaded from assets folder (read-only, keyed by name)
|
||||
public HashMap<String, BuiltInAnimation> builtInAnimations = new HashMap<>();
|
||||
private static final String BUILTIN_ANIMATIONS_PATH = "/assets/customnpcs/animations";
|
||||
private static final String BUILTIN_ANIMATIONS_RESOURCE = "assets/customnpcs/animations";
|
||||
private static final String BUILTIN_ANIMATIONS_PATH = "/assets/customnpcs/cnpc_animations";
|
||||
private static final String BUILTIN_ANIMATIONS_RESOURCE = "assets/customnpcs/cnpc_animations";
|
||||
|
||||
public static AnimationController Instance = new AnimationController();
|
||||
private int lastUsedID = 0;
|
||||
@@ -75,7 +75,7 @@ public class AnimationController implements IAnimationHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Load built-in animations from assets/customnpcs/animations/ folder.
|
||||
* Load built-in animations from assets/customnpcs/cnpc_animations/ folder.
|
||||
* These animations are read-only and accessed by name only (no IDs).
|
||||
* Scans the folder directly instead of using a manifest.
|
||||
*/
|
||||
@@ -311,6 +311,28 @@ public class AnimationController implements IAnimationHandler {
|
||||
return false;
|
||||
}
|
||||
|
||||
public Animation cloneAnimation(int originalId) {
|
||||
Animation original = animations.get(originalId);
|
||||
if (original == null || original instanceof BuiltInAnimation) return null;
|
||||
|
||||
int originalCatId = categoryManager.getItemCategory(originalId);
|
||||
|
||||
Animation clone = new Animation();
|
||||
clone.readFromNBT(original.writeToNBT());
|
||||
clone.id = getUnusedId();
|
||||
|
||||
String name = clone.name;
|
||||
while (hasName(name)) name += "_";
|
||||
clone.name = name;
|
||||
|
||||
if (originalCatId > CategoryManager.UNCATEGORIZED_ID) {
|
||||
categoryManager.registerItem(clone.id, originalCatId);
|
||||
}
|
||||
|
||||
saveAnimation(clone);
|
||||
return clone;
|
||||
}
|
||||
|
||||
public void delete(String name) {
|
||||
Animation delete = getAnimationFromName(name);
|
||||
if (delete != null) {
|
||||
|
||||
@@ -712,6 +712,8 @@ public class CustomEffectController implements ICustomEffectHandler {
|
||||
CustomEffect original = getCustomEffects().get(originalId);
|
||||
if (original == null) return null;
|
||||
|
||||
int originalCatId = categoryManager.getItemCategory(originalId);
|
||||
|
||||
NBTTagCompound nbt = original.writeToNBT(true);
|
||||
int newId = getUnusedId();
|
||||
nbt.setInteger("ID", newId);
|
||||
@@ -723,6 +725,10 @@ public class CustomEffectController implements ICustomEffectHandler {
|
||||
while (has(name)) name += "_";
|
||||
clone.name = name;
|
||||
|
||||
if (originalCatId > CategoryManager.UNCATEGORIZED_ID) {
|
||||
categoryManager.registerItem(newId, originalCatId);
|
||||
}
|
||||
|
||||
saveEffect(clone);
|
||||
return clone;
|
||||
}
|
||||
|
||||
@@ -245,6 +245,8 @@ public class LinkedItemController implements ILinkedItemHandler {
|
||||
LinkedItem original = linkedItems.get(originalId);
|
||||
if (original == null) return null;
|
||||
|
||||
int originalCatId = categoryManager.getItemCategory(originalId);
|
||||
|
||||
NBTTagCompound nbt = original.writeToNBT(true);
|
||||
int newId = getUnusedId();
|
||||
nbt.setInteger("Id", newId);
|
||||
@@ -256,6 +258,10 @@ public class LinkedItemController implements ILinkedItemHandler {
|
||||
while (hasName(name)) name += "_";
|
||||
clone.name = name;
|
||||
|
||||
if (originalCatId > CategoryManager.UNCATEGORIZED_ID) {
|
||||
categoryManager.registerItem(newId, originalCatId);
|
||||
}
|
||||
|
||||
saveLinkedItem(clone);
|
||||
return clone;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package noppes.npcs.controllers.data;
|
||||
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.nbt.NBTTagList;
|
||||
import net.minecraftforge.common.util.Constants;
|
||||
import noppes.npcs.api.handler.data.IQuest;
|
||||
import noppes.npcs.api.handler.data.IQuestCategory;
|
||||
|
||||
@@ -21,8 +22,8 @@ public class QuestCategory implements IQuestCategory {
|
||||
public void readNBT(NBTTagCompound nbttagcompound) {
|
||||
id = nbttagcompound.getInteger("Slot");
|
||||
title = nbttagcompound.getString("Title");
|
||||
NBTTagList questList = nbttagcompound.getTagList("Quests", 10);
|
||||
if (questList != null) {
|
||||
NBTTagList questList = getFirstValidList(nbttagcompound, Constants.NBT.TAG_COMPOUND, "Quests", "Dialogs");
|
||||
if (questList.tagCount() > 0) {
|
||||
for (int ii = 0; ii < questList.tagCount(); ii++) {
|
||||
NBTTagCompound nbttagcompound2 = questList.getCompoundTagAt(ii);
|
||||
Quest quest = new Quest();
|
||||
@@ -33,6 +34,18 @@ public class QuestCategory implements IQuestCategory {
|
||||
}
|
||||
}
|
||||
|
||||
private NBTTagList getFirstValidList(NBTTagCompound nbt, int type, String... keys) {
|
||||
for (String key : keys) {
|
||||
if (nbt.hasKey(key, Constants.NBT.TAG_LIST)) {
|
||||
NBTTagList list = nbt.getTagList(key, type);
|
||||
if (list.tagCount() > 0) {
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new NBTTagList();
|
||||
}
|
||||
|
||||
public NBTTagCompound writeNBT(NBTTagCompound nbttagcompound) {
|
||||
nbttagcompound.setInteger("Slot", id);
|
||||
nbttagcompound.setString("Title", title);
|
||||
|
||||
@@ -49,10 +49,16 @@ public class EnergyProjectileEvent extends CustomNPCsEvent implements IEnergyPro
|
||||
* energyProjectileTick
|
||||
*/
|
||||
public static class UpdateEvent extends EnergyProjectileEvent implements IEnergyProjectileEvent.UpdateEvent {
|
||||
public UpdateEvent(IEnergyProjectile projectile) {
|
||||
private final int tick;
|
||||
|
||||
public UpdateEvent(IEnergyProjectile projectile, int tick) {
|
||||
super(projectile);
|
||||
this.tick = tick;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTick() { return this.tick; }
|
||||
|
||||
@Override
|
||||
public String getHookName() {
|
||||
return EnumScriptType.ENERGY_PROJECTILE_TICK.function;
|
||||
|
||||