Compare commits

..
Author SHA1 Message Date
KAMKEEL 0dc0e72b62 Revert the NPC tool click guard; Backhand now drops the offhand click itself 2026-10-06 01:58:05 -04:00
KAMKEEL 8f4fcae735 Using the Wand, Scripter or Cloner on an NPC no longer runs its interact through an offhand click 2026-10-06 01:51:13 -04:00
KAMKEEL 2c29f11550 Skin overlays keep the world's light directions instead of lighting from below 2026-10-06 01:51:13 -04:00
KAMKEEL cc2a1246d5 Stop the script editor typing each key twice under lwjgl3ify 2026-10-01 03:48:44 -04:00
KAMKEEL 5712541cae Stop the mount reset clearing a flying npc's flying flag every tick 2026-10-01 03:03:19 -04:00
KAMKEEL 9a7758a27b Cut wasted NPC tick work and stop the flying flag flipping every tick 2026-10-01 02:58:31 -04:00
KAMKEEL cf1e34b4a7 Smooth fast energy projectiles 2026-09-18 15:11:07 -04:00
KAMKEEL 3ecf0a8970 Skip inactive player pose work 2026-09-18 04:48:54 -04:00
KAMKEEL dbbca1c4ec Keep player pose for held items 2026-09-18 04:19:11 -04:00
KAMKEEL 3ee0df1865 Optional Late Mixins 2026-09-17 19:45:03 -04:00
KAMKEEL 3d530a207a Trace entry into the MPM player model 2026-09-17 18:51:16 -04:00
KAMKEEL fcb3384e5f Apply animations at the MPM model pose boundary 2026-09-17 18:50:20 -04:00
KAMKEEL 2ef2936496 Make MPM animation hooks fail loud and traceable 2026-09-17 18:38:31 -04:00
KAMKEEL e910691279 Animate MorePlayerModels limbs through the optional render mixin 2026-09-17 18:25:52 -04:00
KAMKEEL 3b039f67af Keep the script editor out of keys meant for another box 2026-09-10 04:10:09 -04:00
KAMKEEL 517ccb09c3 Drop the shutdown flush that does not compile
The FMLServerStoppingEvent handler added in 1.11.2-beta1 calls
PlayerData.flushEffects() and PlayerData.save(boolean), and neither method
exists -- so the mod has not compiled since that commit.

Removed along with the four imports the same commit added for it:
FMLServerStoppingEvent, EntityPlayer, PlayerData and ArrayList. Nothing else in
the class used them, so CustomNpcs.java now differs from 8612d444 only by the
version bump.

The problem it was written for is real -- effects live in memory, and logout is
not guaranteed to fire during shutdown -- but the flush needs methods that have
to be written first.
2026-08-14 00:32:35 -04:00
KAMKEEL 5403060ee5 1.11.2-beta1 2026-08-13 23:14:01 -04:00
KAMKEEL 8612d4442a Restore the npc step height even if the hitbox nudge throws 2026-08-13 06:06:14 -04:00
KAMKEEL b6f2bae770 Stop the hitbox nudge stepping npcs up when they lie down 2026-08-13 03:02:03 -04:00
KAMKEEL e3a1017770 Remove the hitbox investigation logging 2026-08-11 17:35:19 -04:00
KAMKEEL 7f606fbec2 Disable the hitbox grow nudge while testing 2026-08-11 15:47:50 -04:00
KAMKEEL 3dfcf7764a Log client interpolation state alongside the hitbox probe 2026-08-11 15:38:55 -04:00
KAMKEEL 1a1871f803 Keep the hitbox logging from forcing a chunk load during entity load 2026-08-11 15:16:33 -04:00
KAMKEEL 277c056417 Add temporary hitbox logging for the npc clipping investigation 2026-08-11 15:11:57 -04:00
KAMKEEL c634c4bd35 Revert "Refresh block bounds before reading a collision box so top slabs report the right height"
This reverts commit 715b38e694.
2026-08-11 15:09:59 -04:00
KAMKEEL 715b38e694 Refresh block bounds before reading a collision box so top slabs report the right height 2026-08-11 14:59:09 -04:00
KAMKEEL 9ff4b8ae16 Nudge npcs out of blocks they grow into when the hitbox changes 2026-08-11 12:53:08 -04:00
KAMKEEL e3d1c9b1a7 Apply the entity tracker spawn fix on the integrated server too 2026-08-11 12:29:57 -04:00
KAMKEEL 605907681c Return npcs to their start position when they fall out of the world 2026-08-11 12:29:56 -04:00
KAMKEEL 32c5cc78c7 Stop cloning a linked item from replacing its shared script handler 2026-08-11 12:18:59 -04:00
KAMKEEL 795464fb81 Key the skin overlay packet on UUID so it isn't dropped for unloaded players 2026-08-11 12:18:59 -04:00
KAMKEEL 4a52690d99 Let a script reload clear the errored latch on single-container handlers 2026-08-11 12:18:59 -04:00
KAMKEEL fae2c21893 Fix the script-facing effect apply and remove overloads throwing on every call 2026-08-11 12:18:59 -04:00
KAMKEEL c2ad3ef015 Small Behavior Restorations 2026-08-11 12:00:52 -04:00
KAMKEEL 98c94bd406 Trim comments 2026-08-11 11:32:01 -04:00
KAMKEEL f175e3fb82 Merge pull request #254 from Kirill Epifanov: code cleanup and null-safety fixes 2026-08-11 06:29:18 -04:00
KAMKEEL 67ddaaab6f Keep entity hash consistent with equals, and campfire interaction handled
ScriptEntity.hashCode included tempData while equals compares only the entity,
so two wrappers of the same entity hashed differently - and tempData is mutable
and swapped wholesale by copyTempData, so an entry's hash could change while it
sat in a map.

BlockCampfire.onBlockActivated went from returning true to false, which lets the
held item be used or placed on top of the interaction. Restored.
2026-08-11 06:29:18 -04:00
KAMKEEL 22a8ef5036 Merge branch 'dev' into pr-254
# Conflicts:
#	src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerSelector.java
2026-08-11 06:29:18 -04:00
KAMKEEL 2de0795a8e Keep the pBurnItem migration on revision 23
Revision 23 never shipped without the burn flag - it released together with it -
so no saved NPC carries version 23 from a build that lacked pBurnItem. The
migration belongs in the < 23 gate, and bumping ModRev would only force a
redundant pass over every NPC.
2026-08-11 06:07:58 -04:00
KAMKEEL 3193a2bfc3 Merge pull request #290 from postyizhan: register inventory tabs after mod loading completes 2026-08-11 05:56:08 -04:00
KAMKEEL c6e361f8e6 Register inventory tabs from the client proxy, not the mod class
Deferring registration to loadComplete is right - TConstruct needs to have
registered first - but naming TabRegistry and the tab classes in CustomNpcs put
client-only GUI types in a class the server loads, which the verifier resolves
at link time regardless of any runtime side check. A proxy hook keeps them in
ClientProxy while still running at the same point.
2026-08-11 05:56:08 -04:00
KAMKEEL 74511b7449 Merge branch 'dev' into pr-290
# Conflicts:
#	src/api
2026-08-11 05:54:41 -04:00
KAMKEEL 3535e7b819 Merge pull request #293 from Mighty-S0715: reassign colliding dialog IDs instead of discarding 2026-08-11 05:54:14 -04:00
KAMKEEL 179fd4f834 Make ID reassignment safe, and apply it to quests too
The free-ID search only consulted the global map, so it could pick an id the
same category still held further down the iteration - and renameTo silently
overwrites on POSIX, so the rename then destroyed that entry's file. It now
skips ids held by the category and any file already on disk.

Quests had the same discard-on-collision behaviour and now get the same
reassignment, including re-registering shared quests under the new id.
2026-08-11 05:54:14 -04:00
KAMKEEL 1d0b640c61 Merge branch 'dev' into pr-293 2026-08-11 05:52:42 -04:00
KAMKEEL d4b9a18a1a Merge pull request #278 from zeng-github01: fix pEffect legacy compatibility 2026-08-11 05:52:36 -04:00
KAMKEEL fab1062ce8 Bump ModRev so the pBurnItem migration can run
The migration sat in the npcVersion < 17 block, but ModRev has been 23 since
2023 and CheckNpcCompatibility returns early when the save already matches it -
so every NPC affected by the regression was skipped. Moved to a < 24 block and
bumped ModRev to 24 so it actually reaches them.
2026-08-11 05:52:30 -04:00
KAMKEEL 1532ef722c Merge branch 'dev' into pr-278 2026-08-11 05:51:40 -04:00
KAMKEEL caa39d6d5d Merge pull request #283 from zeng-github01: disable auto-open GUI for BlockBorder and BlockNpcRedstone 2026-08-11 05:22:36 -04:00
KAMKEEL a71532f49a Merge pull request #292 from postyizhan: adapt quest tracker height to content 2026-08-11 05:22:35 -04:00
KAMKEEL a028142dda Fix mouse wheel scrolling in the script editors
Mouse.getDWheel() clears the accumulated delta, so whichever widget polled it
first in a frame took it and every later reader saw zero. The script text areas
polled it themselves, after the parent screen had already drained it for its
scroll lists, so the wheel did nothing in the player, NPC and event script GUIs.
The screen now reads the wheel once per frame into the mouseScroll field it
already declared for this, and each widget zeroes it when it consumes it.
2026-08-11 05:08:15 -04:00
KAMKEEL 71bb4b451e Honour the effective windup instead of the raw field
start() and tick() compared against the raw windUpTicks, but when the windup is
synced to an animation the value that applies comes from getWindUpTicks(). An
ability configured that way skipped its windup entirely and fired on the first
tick. The telegraph duration used the raw field too, so it disagreed with the
phase it was meant to cover.
2026-08-11 05:01:50 -04:00
KAMKEEL 677d50fa03 Keep client-only sub-GUI types out of condition and zone descriptors
Same leak as the ability magic editor: @SideOnly strips the annotated method on a
server but not the synthetic lambdas it generates, so ConditionHasEffect,
ConditionQuestCompleted, AbilityTrap and AbilityZone all shipped methods whose
descriptors named a client-only GUI class. Each field is now built in the GUI
class it belongs to.
2026-08-11 05:00:02 -04:00
KAMKEEL 466b49db5e Let the day/night transform actually fire
EntityAITransform claimed the PASSIVE mutex, so any running movement or look
task blocked it from ever starting. The swap only happened in the gaps where
those yielded - which is why it appeared to trigger when an NPC said a line and
for a moment afterwards. The task only polls world time and flips the state, so
it needs no mutex at all.
2026-08-11 04:52:50 -04:00
KAMKEEL dedbe94cd8 Keep client-only sub-GUI types out of Ability's method descriptors
The magic editor field was built with lambdas inside Ability.getAllDefinitions.
subGuiField is generic, so those lambdas took SubGuiAbilityMagic as their
descriptor type. @SideOnly strips the annotated method on a server but not the
synthetic lambdas it generates, so anything reflecting over Ability's declared
methods - Nashorn's adapter generator when a script touches an ability - hit
NoClassDefFoundError. Building the field in the client class keeps the type out
of Ability entirely.
2026-08-11 04:44:14 -04:00
KAMKEEL c79f5998d6 Stop NPC pathfinding fighting Charge's own movement
Charge drives the NPC with applyVelocityFlat but never declared that it does, so
locking movement during the active phase zeroed its motion outright while not
locking left the navigator running against it - no setting worked. It now
declares its own movement and locks both phases, so the navigator stays clear.
2026-08-11 04:24:40 -04:00
KAMKEEL 1acda0e6b0 Scale hazard damage to its interval and floor the interval at 5 ticks
The value is configured, stored and labelled as damage per second, but a pulse
applied it whole, so the real rate was damage per interval - it only matched at
the default interval of 20. A pulse now deals the share of a second it covers.
The interval is floored at 5 ticks, which also bounds how often a zone scans;
this replaces the per-tick membership check, which cost 20x the entity queries.
2026-08-11 04:23:59 -04:00
KAMKEEL 4341c15cf4 Scale melee damage dealt to barriers
Barriers are plain entities, so no LivingHurtEvent fires for them and nothing
scaled an incoming melee hit - vanilla handed over the bare attackDamage
attribute and a dome took one point per swing however strong the attacker was.
Attributes now apply, and modifyBarrierMeleeDamage gives addons the same seam
they already have for barrier health.
2026-08-11 03:43:38 -04:00
KAMKEEL 6477ede022 Make hazard radius and barrier duration accurate
- Hazards only checked who was inside once per damage interval, so the boundary
  where damage started and stopped drifted by however far an entity moved in
  between - several blocks at sprint speed. Membership is now checked every
  tick and damage accrues per entity from the time it actually spends inside.
- Barriers counted elapsed ticks instead of holding a deadline, so every tick
  the entity missed extended it past its configured duration. They now expire
  on an absolute world time like the other energy entities.
2026-08-11 03:43:38 -04:00
KAMKEEL 7cafa4f677 Make anchored lasers and rotation lock affect ability aim
- Anchored lasers re-derived their direction straight at the target every tick,
  discarding the rate-limited look vector, so track speed did nothing and the
  beam was undodgeable. They now converge on the point the owner is aiming at.
- Rotation-locked NPCs aimed energy projectiles and hit-scan projectiles from
  the target''s position, so the lock was purely visual. Both now respect the
  frozen heading.
2026-08-11 03:43:37 -04:00
KAMKEEL 9f4334a803 Line the monkey tail up with the player model
heightFactor did not fully cancel ModelTail''s anchor, leaving both the wrapped
and plain monkey tails two pixels below where JBRA renders them on players.
2026-08-11 03:26:32 -04:00
KAMKEEL 6af66b8883 Fix NPCs getting stuck after using one ability
The terminal DAZED to IDLE transition was swallowed before the completion
switch ran, so the finished ability stayed set as the current one and the NPC
never started another until it died and reset. Guard abilities compounded it:
NPCs reuse a single ability instance and onExecute left pendingCompletion set,
ending every later activation on its first tick.
2026-08-11 03:25:51 -04:00
KAMKEEL abd1c7cbeb Make per-ability cooldowns work on NPCs
An NPC rolled both clocks and folded the ability''s cooldown into the global one
as well, so the global timer always outlasted the per-ability entry and the
setting could never reject anything. The global timer now only paces the NPC
when the ability tracks its own cooldown.
2026-08-11 03:24:59 -04:00
KAMKEEL 3565c66cf8 Keep ability cooldowns across logout
Dimension change and teleport were already fixed, but disconnect still cleared
cooldowns and login cleared them again, and they were never written to NBT - so
relogging reset every cooldown. They are absolute world-time deadlines, so they
now persist and are restored on load.
2026-08-11 03:24:19 -04:00
KAMKEEL aaf6734bd9 Take deleted abilities away from players properly
Deleting a custom ability only cleared the unlocked list. An active toggle kept
a direct reference and went on ticking, stale hotbar slots survived, and the
client was never resynced so it still showed and could select the ability.
Selecting a key the player no longer has now deselects instead of firing
whatever was previously selected.
2026-08-11 03:22:56 -04:00
KAMKEEL 68b5191db6 Fix trader edits being lost on an existing linked market
Closing the setup GUI saved the market from the server''s stale role and then
re-read that market over the edits it had just applied, so stock and currency
cost changes never survived. The role now saves first and the market is written
from it, and relinking to another market no longer pushes pre-link data over it.
2026-08-11 03:21:46 -04:00
KAMKEEL 17f61de57a Fix editor StackOverflow on self-referential generic bounds
fromGenericType expanded a type variable bound, then expanded the bound''s type
arguments, which led straight back to the same variable. Any enum reaches it
through Enum<E extends Enum<E>>, so typing ability.getAllowedBy() crashed the
client. Track the variables being expanded and emit repeats unbounded.
2026-08-11 03:20:34 -04:00
KAMKEEL 5aa843966a Fix divide by zero clicking the profiles scrollbar
The scrollbar hit test was pure geometry, so clicking its column before the
profile list had loaded - or on any list short enough not to scroll - divided
by a maxScrollY of zero. The draw path already guarded on the same value.
2026-08-11 03:19:52 -04:00
KAMKEEL 0829b6285f Update EntityNPCInterface.java 2026-08-11 02:17:28 -04:00
Mighty-S0715 2c134fe627 fix(dialogs): reassign colliding dialog IDs instead of discarding 2026-08-02 12:31:50 -04:00
postyizhan 322626015d fix: adapt quest tracker height to content 2026-08-02 22:32:00 +08:00
LLEVC 50e16dc538 the one change i wanted to make 2026-06-25 18:32:36 -07:00
KAMKEEL 4a7c7b09c7 - Fix Counter infinite recursion
- Tags Get Packet
- Cooldowns Resetting on Dimension Change / Teleport
2026-04-20 21:00:54 -04:00
bigguy345 1a77728bcd OVERHAULED IGuiData FRAMEWORK SO ALL UPDATES WIRE THROUGH SyncController (deprecated legacy setGuiData) 2026-04-03 18:00:27 +02:00
bigguy345 7f63b64a66 Set ScriptHandler default to enabled = true 2026-04-03 16:32:56 +02:00
bigguy345 8e8ab06507 Fixed janino script handler serialization inconsistencies 2026-04-03 16:32:34 +02:00
bigguy345 4c301b3c1c Improved PlayerDataSyncHandler 2026-04-02 04:29:29 +02:00
bigguy345 67c6cf14d3 SyncController common SyncRegistry registration (SyncTypes must be on client & server) 2026-04-02 04:26:49 +02:00
bigguy345 0a4bc4126f Fixed massive SyncPacket failure 2026-04-02 04:09:20 +02:00
zeng-github01 b8d68f771f refactor: disable auto-open GUI for BlockBorder and BlockNpcRedstone
- Removed auto-open GUI logic upon placing BlockBorder and BlockNpcRedstone.
- Resolved a race condition where the GUI would open before NBT/Permission data was fully synced from the server, causing "Permission Denied" or empty states.
- Fixed a logic bug in SubGuiNpcAvailabilityDialog where 'questId' was incorrectly used instead of 'dialogId' when opening the selection picker.
- This change ensures better UX as manual interaction guarantees all data is properly initialized.
2026-04-02 08:58:09 +08:00
bigguy345 332f1bfd57 juhhh in case 2026-04-02 00:30:36 +02:00
bigguy345 facee7c388 Expanded SyncController scope to allow syncing based on string operation keys instead of just int ids (i.e ability keys) 2026-04-02 00:24:15 +02:00
bigguy345 22de352dd9 FAAAAAH 2026-03-31 22:57:09 +02:00
bigguy345 b28ea7226f SyncController OVERHAUL PHASE #3:
- Clean up, reorganization and documentation
2026-03-31 22:55:42 +02:00
bigguy345 6d0655ad7d SyncController OVERHAUL PHASE #2:
- Created SyncRegistry and SyncHandler
- Extracted all 14 SyncType family handling to their own SyncHandler
- Rewritten SyncController to accomodate the new framework
2026-03-31 21:44:23 +02:00
bigguy345 48281c8d34 SyncController OVERHAUL PHASE #1:
- Refactored EnumSyncType into object based SyncType registry, so other mods can register their own types
2026-03-31 19:59:53 +02:00
zeng-github01 948eb91b42 Fixes 2026-03-29 10:25:02 +08:00
zeng-github01 07a914272a Fix pEffect legacy Compatibility 2026-03-29 10:19:32 +08:00
bigguy345 b2c279feeb Extra registry methods 2026-03-27 00:01:33 +02:00
Vidal b8cac96c46 Color overrides 2026-03-22 19:36:30 -03:00
Vidal 554fbeb1a8 Made Register constructor protected instead of private 2026-03-22 10:41:14 -03:00
somehussar e0a6bac642 Lobotomize stencil bit enforcement. 2026-03-20 03:08:03 +01:00
Kam f6e7809a29 Fix Auction House ID Saving 2026-03-15 18:23:14 -04:00
Kam 85ef28ca76 Fix DataScript Issue Global API Objects 2026-03-15 18:03:17 -04:00
Kam f4062f3edd Fix Script Container Issue 2026-03-15 14:43:07 -04:00
Kam 92133afe75 Fix issue with Finish Quest API 2026-03-15 00:09:56 -04:00
Vidal b989a89889 AbilityDefend event 2026-03-13 20:48:25 -03:00
Kam edf5ff7c73 Chained Ability Cooldown on NPCs 2026-03-13 18:54:18 -04:00
Kam ab60fdbd12 Fix Chained Ability Icons + Chained Ability Per Cooldown Config Options 2026-03-13 18:52:17 -04:00
Kam ac953685c8 Mob Spawner / Job Spawner Selection Fixes for Folder Support 2026-03-13 18:43:53 -04:00
Kirill Epifanov 9b52c8088e Merge branch 'KAMKEEL:dev' into dev 2026-02-09 22:55:44 +03:00
Mark 524c014fc2 remove double 'if' 2026-02-01 01:30:44 +03:00
Mark a31638f05f reorder textColor 2026-02-01 01:27:54 +03:00
Mark 415de16917 fix syncronization
The String object is located in the string pool and may cause poor synchronization.
2026-02-01 01:19:30 +03:00
Mark 613bb7a2b5 fix comparing classes compared by their name
Other mods may have the same class names.
2026-02-01 01:15:27 +03:00
Mark 3d789cdf3a fix potential NPE 2026-02-01 01:11:08 +03:00
Mark 17d8c99e8b add a hash code to the equals method 2026-02-01 01:10:27 +03:00
Mark 605466e011 fix potential NPE and regex logic 2026-01-31 19:12:12 +03:00
Mark 4535d2ba7f refactor strange code 2026-01-31 18:57:59 +03:00
Mark f96b6ad020 remove "sendOpenGuiNoDelay" method
it is completely equivalent to "sendOpenGui"
2026-01-31 18:54:44 +03:00
Mark 698fcf20ab remove unnecessary check 2026-01-31 18:47:19 +03:00
Mark 66afe80c3c play swing animation only on success 2026-01-31 18:38:58 +03:00
Mark 529ee63866 event should also be canceled on the client 2026-01-31 18:32:10 +03:00
Mark d20c701635 reorder checks 2026-01-31 18:27:06 +03:00
Mark 3be5e2ebb5 remove unnecessary assign 2026-01-31 18:20:34 +03:00
163 changed files with 5068 additions and 1554 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ plugins {
id "dts.typescript-generator"
}
version = "1.11.1"
version = "1.11.2"
group= "kamkeel.customnpc-plus"
archivesBaseName = "CustomNPC-Plus"
+1 -1
View File
@@ -199,7 +199,7 @@ disableCheckstyle = true
# ideaCheckSpotlessOnBuild = true
# Non-GTNH properties
modVersion = 1.11.0
modVersion = 1.11.2
# Increase Gradle's JVM memory usage to avoid daemon expiration due to
# insufficient heap space on CI builds.
+1 -1
Submodule src/api updated: 04fd348d13...e7f363727e.
+2 -1
View File
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.command.CommandBase;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.NoppesUtilServer;
@@ -90,7 +91,7 @@ public class CmdDialog extends ChMcLogger {
)
public boolean reload(String args[]) {
new DialogController().load();
SyncController.syncAllDialogs();
SyncController.syncAll(SyncType.DIALOG_CATEGORY);
return true;
}
+2 -1
View File
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -170,7 +171,7 @@ public class CmdQuest extends ChMcLogger {
)
public boolean reload(String args[]) {
new QuestController().load();
SyncController.syncAllQuests();
SyncController.syncAll(SyncType.QUEST_CATEGORY);
return true;
}
}
@@ -38,6 +38,9 @@ public abstract class RenderEnergy extends Render {
*/
protected boolean shouldSkipInitialActiveRender(Entity entity) {
if (!(entity instanceof EntityEnergyAbility)) return false;
// Moving projectiles must be visible at their launch point. Hiding their first
// tick makes faster shots first appear several blocks away from the caster.
if (entity instanceof EntityEnergyProjectile) return false;
EntityEnergyAbility ability = (EntityEnergyAbility) entity;
return !ability.isPreviewMode() && !ability.isCharging() && ability.ticksExisted <= HIDE_INITIAL_ACTIVE_TICKS;
}
@@ -4,6 +4,8 @@ import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import org.lwjgl.opengl.GL11;
import java.util.Objects;
/**
* 3D Vector helper class for lightning calculations.
* Adapted from Botania's Vector3 by ChickenBones.
@@ -181,4 +183,9 @@ public class Vec3d {
Vec3d v = (Vec3d) o;
return x == v.x && y == v.y && z == v.z;
}
@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
}
@@ -1,6 +1,7 @@
package kamkeel.npcs.command;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
@@ -93,7 +94,7 @@ public class DialogCommand extends CommandKamkeelBase {
)
public void reload(ICommandSender sender, String args[]) {
new DialogController().load();
SyncController.syncAllDialogs();
SyncController.syncAll(SyncType.DIALOG_CATEGORY);
sendResult(sender, "Dialogs Reloaded");
}
@@ -2,6 +2,7 @@ package kamkeel.npcs.command;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.command.CommandException;
@@ -393,7 +394,7 @@ public class QuestCommand extends CommandKamkeelBase {
)
public void reload(ICommandSender sender, String args[]) {
new QuestController().load();
SyncController.syncAllQuests();
SyncController.syncAll(SyncType.QUEST_CATEGORY);
sendResult(sender, "Quests Reloaded");
}
}
@@ -32,6 +32,7 @@ import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityBeam;
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityDisc;
import kamkeel.npcs.controllers.data.ability.type.energy.AbilityDome;
@@ -44,7 +45,10 @@ import net.minecraftforge.common.util.Constants;
import noppes.npcs.controllers.data.AbilityScript;
import noppes.npcs.controllers.data.ChainedAbilityScript;
import net.minecraft.entity.EntityLivingBase;
import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
import noppes.npcs.LogWriter;
@@ -393,7 +397,7 @@ public class AbilityController implements IAbilityHandler {
customAbilitiesById.put(uuid, ability);
customAbilityRevision++;
LogWriter.script("Saved custom ability: " + name + " [" + uuid + "]");
SyncController.syncAllCustomAbilities();
SyncController.syncAll(SyncType.CUSTOM_ABILITY);
return true;
} catch (Exception e) {
LogWriter.error("Error saving custom ability: " + name, e);
@@ -469,16 +473,30 @@ public class AbilityController implements IAbilityHandler {
pData.abilityData.lockAbility(name);
changed = true;
}
if (uuid != null && !uuid.isEmpty()) {
pData.abilityData.setToggleEntryDirect(uuid, 0);
}
pData.abilityData.setToggleEntryDirect(name, 0);
if (pData.hotbarData != null) {
pData.hotbarData.validateSlots();
}
if (changed) {
pData.save();
}
if (pData.player instanceof EntityPlayerMP) {
PlayerAbilitySyncHelper.syncAbilities((EntityPlayerMP) pData.player);
}
}
}
}
customAbilityRevision++;
LogWriter.script("Deleted custom ability: " + name);
SyncController.syncAllCustomAbilities();
SyncController.syncAll(SyncType.CUSTOM_ABILITY);
return true;
}
@@ -765,7 +783,7 @@ public class AbilityController implements IAbilityHandler {
chainedAbilitiesById.put(uuid, chain);
chainedAbilityRevision++;
LogWriter.script("Saved chained ability: " + name + " [" + uuid + "]");
SyncController.syncAllChainedAbilities();
SyncController.syncAll(SyncType.CHAINED_ABILITY);
return true;
} catch (Exception e) {
LogWriter.error("Error saving chained ability: " + name, e);
@@ -845,7 +863,7 @@ public class AbilityController implements IAbilityHandler {
chainedAbilityRevision++;
LogWriter.script("Deleted chained ability: " + name);
SyncController.syncAllChainedAbilities();
SyncController.syncAll(SyncType.CHAINED_ABILITY);
return true;
}
@@ -1362,6 +1380,17 @@ public class AbilityController implements IAbilityHandler {
return health;
}
/**
* Fire modifyBarrierMeleeDamage on all extenders. Cumulative — each extender's output feeds the next.
*/
public float fireModifyBarrierMeleeDamage(EntityEnergyBarrier barrier, EntityLivingBase attacker, float baseDamage) {
float damage = baseDamage;
for (IAbilityExtender ext : extenders) {
damage = ext.modifyBarrierMeleeDamage(barrier, attacker, damage);
}
return damage;
}
/**
* Fire onAbilityHeal on all extenders. Chain of responsibility — first true wins.
*/
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -840,19 +840,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
return sb.toString();
}).tab("General"));
defs.add(FieldDef.subGuiField("ability.magic.editor",
() -> new SubGuiAbilityMagic(magicData.copy()),
gui -> {
MagicData result = ((SubGuiAbilityMagic) gui).magicData;
magicData.getMagics().clear();
for (Map.Entry<Integer, MagicEntry> e : result.getMagics().entrySet()) {
magicData.getMagics().put(e.getKey(), e.getValue());
}
})
.buttonLabel(() -> magicData.isEmpty()
? StatCollector.translateToLocal("ability.magic.usesCaster")
: magicData.getMagics().size() + " Magic(s)")
.tab("General"));
defs.add(SubGuiAbilityMagic.createMagicField(magicData));
}
// ── Target tab ───────────────────────────────────────────────
@@ -1062,10 +1050,11 @@ public abstract class Ability implements IAbility, IAbilityAction {
return null;
}
telegraph.setDurationTicks(windUpTicks);
int windUp = getWindUpTicks();
telegraph.setDurationTicks(windUp);
telegraph.setColor(windUpColor);
telegraph.setWarningColor(activeColor);
telegraph.setWarningStartTick(Math.max(5, windUpTicks / 4));
telegraph.setWarningStartTick(Math.max(5, windUp / 4));
telegraph.setHeightOffset(telegraphHeightOffset);
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
@@ -1183,7 +1172,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
this.burstIndex = 0;
this.burstEntities.clear();
if (windUpTicks <= 0) {
if (getWindUpTicks() <= 0) {
this.phase = AbilityPhase.ACTIVE;
} else {
this.phase = AbilityPhase.WINDUP;
@@ -1205,7 +1194,7 @@ public abstract class Ability implements IAbility, IAbilityAction {
switch (phase) {
case WINDUP:
if (currentTick >= windUpTicks) {
if (currentTick >= getWindUpTicks()) {
phase = AbilityPhase.ACTIVE;
currentTick = 0;
return true;
@@ -34,27 +34,15 @@ public class ConditionHasEffect extends AbilityCondition {
return CustomEffectController.getInstance().hasEffect(player, effectId, effectIndex);
}
public void setEffect(int effectId, int effectIndex) {
this.effectId = effectId;
this.effectIndex = effectIndex;
}
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.subGuiField("condition.select_effect",
() -> new SubGuiCustomEffectSelect(effectId, effectIndex),
gui -> {
SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui;
if (sel.getSelectedEffectId() >= 0) {
effectId = sel.getSelectedEffectId();
effectIndex = sel.getSelectedIndex();
}
})
.buttonLabel(() -> {
if (effectId < 0) return "None";
CustomEffect effect = getEffect();
return effect != null ? effect.getName() : "ID:" + effectId;
})
.clearable(() -> {
effectId = -1;
effectIndex = 0;
}));
defs.add(SubGuiCustomEffectSelect.createSelectField(this));
}
@SideOnly(Side.CLIENT)
@@ -74,7 +62,7 @@ public class ConditionHasEffect extends AbilityCondition {
return effectId >= 0;
}
private CustomEffect getEffect() {
public CustomEffect getEffect() {
HashMap<Integer, CustomEffect> map = CustomEffectController.getInstance().getEffectMap(effectIndex);
return map != null ? map.get(effectId) : null;
}
@@ -38,20 +38,7 @@ public class ConditionQuestCompleted extends AbilityCondition {
@SideOnly(Side.CLIENT)
@Override
public void getConditionDefinitions(List<FieldDef> defs) {
defs.add(FieldDef.subGuiField("condition.select_quest",
() -> new GuiQuestSelection(questId),
gui -> {
GuiQuestSelection sel = (GuiQuestSelection) gui;
if (sel.selectedQuest != null) {
questId = sel.selectedQuest.id;
}
})
.buttonLabel(() -> {
if (questId < 0) return "None";
Quest q = QuestController.Instance.quests.get(questId);
return q != null ? q.title : "ID:" + questId;
})
.clearable(() -> questId = -1));
defs.add(GuiQuestSelection.createConditionField(this));
}
@SideOnly(Side.CLIENT)
@@ -51,6 +51,16 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
*/
private int cooldownTicks = 100;
/**
* If true, only this chain goes on cooldown (not the global cooldown).
*/
private boolean perAbilityCooldown = false;
/**
* If true, skip cooldown entirely after chain completes.
*/
private boolean ignoreCooldown = false;
/**
* Minimum range for NPC eligibility check.
*/
@@ -159,6 +169,22 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
this.cooldownTicks = Math.max(0, cooldownTicks);
}
public boolean isPerAbilityCooldown() {
return perAbilityCooldown;
}
public void setPerAbilityCooldown(boolean perAbilityCooldown) {
this.perAbilityCooldown = perAbilityCooldown;
}
public boolean isIgnoreCooldown() {
return ignoreCooldown;
}
public void setIgnoreCooldown(boolean ignoreCooldown) {
this.ignoreCooldown = ignoreCooldown;
}
public float getMinRange() {
return minRange;
}
@@ -402,6 +428,8 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
nbt.setInteger("Weight", weight);
nbt.setBoolean("WindUpAll", windUpAll);
nbt.setInteger("CooldownTicks", cooldownTicks);
nbt.setBoolean("PerAbilityCooldown", perAbilityCooldown);
nbt.setBoolean("IgnoreCooldown", ignoreCooldown);
nbt.setFloat("MinRange", minRange);
nbt.setFloat("MaxRange", maxRange);
@@ -443,6 +471,8 @@ public class ChainedAbility implements IChainedAbility, IAbilityAction {
weight = nbt.hasKey("Weight") ? nbt.getInteger("Weight") : 10;
windUpAll = !nbt.hasKey("WindUpAll") || nbt.getBoolean("WindUpAll");
cooldownTicks = nbt.hasKey("CooldownTicks") ? nbt.getInteger("CooldownTicks") : 100;
perAbilityCooldown = nbt.getBoolean("PerAbilityCooldown");
ignoreCooldown = nbt.getBoolean("IgnoreCooldown");
minRange = nbt.getFloat("MinRange");
maxRange = nbt.hasKey("MaxRange") ? nbt.getFloat("MaxRange") : 20;
// AllowedBy is computed from child abilities
@@ -3,6 +3,7 @@ package kamkeel.npcs.controllers.data.ability.extender;
import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import net.minecraft.entity.EntityLivingBase;
/**
@@ -108,6 +109,13 @@ public interface IAbilityExtender {
return baseHealth;
}
/**
* Modify melee damage dealt to a barrier. Cumulative across all extenders.
*/
default float modifyBarrierMeleeDamage(EntityEnergyBarrier barrier, EntityLivingBase attacker, float baseDamage) {
return baseDamage;
}
/**
* Called when an ability is about to heal an entity.
* Return true to handle the healing (skip default entity.heal()).
@@ -43,7 +43,7 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
this.targetingMode = TargetingMode.AGGRO_TARGET;
this.maxRange = 20.0f;
this.minRange = 4.0f;
this.lockMovement = LockMode.WINDUP;
this.lockMovement = LockMode.WINDUP_AND_ACTIVE;
this.cooldownTicks = 0;
this.windUpTicks = 20;
// LINE telegraph showing charge path
@@ -58,6 +58,11 @@ public class AbilityCharge extends AbilityMovement implements IAbilityCharge {
};
}
@Override
public boolean hasAbilityMovement() {
return true; // This ability drives the NPC's motion itself
}
@Override
public boolean isTargetingModeLocked() {
return true;
@@ -3,14 +3,21 @@ package kamkeel.npcs.controllers.data.ability.type;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.addon.DBCAddon;
import noppes.npcs.AbstractDataAbilities;
import noppes.npcs.controllers.AnimationController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.api.ability.type.IAbilityCounter;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.Arrays;
import java.util.List;
@@ -25,6 +32,11 @@ public class AbilityCounter extends AbilityDefend implements IAbilityCounter {
private int counterAnimationId = -1;
private String counterAnimationName = "Ability_Guard_Counter";
// True only while this counter is synchronously dispatching its retaliation damage.
// Another counter that is hit by that retaliation inspects this flag on the source
// entity's active counter to avoid reacting and creating infinite mutual retaliation.
private transient boolean retaliating;
public AbilityCounter() {
this.typeId = "ability.cnpc.counter";
this.name = "Counter";
@@ -60,6 +72,35 @@ public class AbilityCounter extends AbilityDefend implements IAbilityCounter {
// DEFEND HOOKS
// ═══════════════════════════════════════════════════════════════════
@Override
protected boolean isValidDamageSource(DamageSource source) {
if (!super.isValidDamageSource(source)) {
return false;
}
// Break counter-vs-counter recursion: if the hit is itself a retaliation
// from another counter that is mid-dispatch, don't counter it back.
Entity sourceEntity = source.getEntity();
AbstractDataAbilities abilities = getAbilitiesOf(sourceEntity);
if (abilities != null) {
Ability current = abilities.getCurrentAbility();
if (current instanceof AbilityCounter && ((AbilityCounter) current).retaliating) {
return false;
}
}
return true;
}
private static AbstractDataAbilities getAbilitiesOf(Entity entity) {
if (entity instanceof EntityPlayer) {
PlayerData pData = PlayerData.get((EntityPlayer) entity);
return pData != null ? pData.abilityData : null;
}
if (entity instanceof EntityNPCInterface) {
return ((EntityNPCInterface) entity).abilities;
}
return null;
}
@Override
protected float performDefend(EntityLivingBase attacker, float amount) {
// For PERCENT mode with DBC, use the full DBC-calculated damage, not vanilla base
@@ -78,13 +119,24 @@ public class AbilityCounter extends AbilityDefend implements IAbilityCounter {
// Counter-attack through the standard ability damage pipeline.
// DBCAbilityExtender handles DBC stat routing (ignore flags, scaling, etc.) automatically.
if (caster != null && attacker.isEntityAlive() && damage > 0) {
applyAbilityDamage(caster, attacker, damage, 0);
if (caster != null && attacker != null && attacker.isEntityAlive() && damage > 0) {
retaliating = true;
try {
applyAbilityDamage(caster, attacker, damage, 0);
} finally {
retaliating = false;
}
}
return 0;
}
@Override
public void reset() {
super.reset();
retaliating = false;
}
// ═══════════════════════════════════════════════════════════════════
// OVERRIDES
// ═══════════════════════════════════════════════════════════════════
@@ -10,9 +10,11 @@ import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import noppes.npcs.EventHooks;
import noppes.npcs.api.ability.type.IAbilityDefend;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.controllers.data.Animation;
import noppes.npcs.scripted.event.AbilityEvent;
import java.util.List;
@@ -72,6 +74,10 @@ public abstract class AbilityDefend extends Ability implements IAbilityDefend {
hitCount = 0;
lastAttacker = null;
lastDamageTaken = 0.0f;
pendingDefendAnimation = null;
defendAnimEndTick = -1;
lastDefendTick = -1;
pendingCompletion = false;
}
@Override
@@ -147,8 +153,14 @@ public abstract class AbilityDefend extends Ability implements IAbilityDefend {
}
}
//inject defend event
AbilityEvent.DefendEvent event = new AbilityEvent.DefendEvent(caster, this, attacker, lastAttacker, amount);
if (EventHooks.onAbilityDefend(this, event)) {
return event.getDamage();
}
// Always calculate the correct reduction for the caller's damage amount
return performDefend(attacker, amount);
return performDefend(attacker, event.getDamage());
}
/**
@@ -107,7 +107,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard {
readZoneNBT(nbt, 300);
this.radius = nbt.getFloat("radius");
this.damagePerSecond = nbt.getFloat("damagePerSecond");
this.damageInterval = nbt.getInteger("damageInterval");
setDamageInterval(nbt.getInteger("damageInterval"));
this.affectsCaster = nbt.getBoolean("affectsCaster");
}
@@ -138,7 +138,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard {
}
public void setDamageInterval(int damageInterval) {
this.damageInterval = damageInterval;
this.damageInterval = Math.max(EntityAbilityZone.MIN_DAMAGE_INTERVAL, damageInterval);
}
public boolean isAffectsCaster() {
@@ -171,6 +171,7 @@ public class AbilityHazard extends AbilityZone implements IAbilityHazard {
FieldDef.row(
FieldDef.floatField("gui.dps", this::getDamagePerSecond, this::setDamagePerSecond),
FieldDef.intField("gui.interval", this::getDamageInterval, this::setDamageInterval)
.range(EntityAbilityZone.MIN_DAMAGE_INTERVAL, 2000)
),
FieldDef.boolField("ability.affectsCaster", this::isAffectsCaster, this::setAffectsCaster)
.hover("ability.hover.affectsCaster"),
@@ -97,6 +97,13 @@ public class AbilityProjectile extends Ability implements IAbilityProjectile {
dz /= len;
}
if (isRotationLockedForCurrentPhase()) {
Vec3 look = caster.getLookVec();
if (look != null && (dx * look.xCoord + dy * look.yCoord + dz * look.zCoord) < 0.95) {
return;
}
}
applyAbilityDamageWithDirection(caster, target, damage, knockback, dx, dz);
world.playSoundAtEntity(caster, "random.bow", 1.0f, 0.8f);
@@ -300,14 +300,7 @@ public class AbilityTrap extends AbilityZone implements IAbilityTrap {
@SideOnly(Side.CLIENT)
@Override
protected void addPresetFieldDef(List<FieldDef> defs) {
defs.add(FieldDef.subGuiField("gui.applyPreset",
SubGuiTrapPresetSelector::new,
gui -> {
SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui;
if (selector.selectedPreset != null) {
applyTrapPresetDefaults(selector.selectedPreset);
}
}));
defs.add(SubGuiTrapPresetSelector.createPresetField(this::applyTrapPresetDefaults));
}
@SideOnly(Side.CLIENT)
@@ -690,14 +690,7 @@ public abstract class AbilityZone extends Ability {
@SideOnly(Side.CLIENT)
protected void addPresetFieldDef(List<FieldDef> defs) {
defs.add(FieldDef.subGuiField("gui.applyPreset",
SubGuiZonePresetSelector::new,
gui -> {
SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui;
if (selector.selectedPreset != null) {
applyPresetDefaults(selector.selectedPreset);
}
}));
defs.add(SubGuiZonePresetSelector.createPresetField(this::applyPresetDefaults));
}
@SideOnly(Side.CLIENT)
@@ -248,7 +248,9 @@ public abstract class AbilityEnergyProjectile<E extends EntityEnergyProjectile>
* NPCs use their resolved target so launch math can track the target immediately.
*/
protected EntityLivingBase getLaunchTarget(EntityLivingBase caster, EntityLivingBase target) {
return isPlayerCaster(caster) ? null : target;
if (isPlayerCaster(caster)) return null;
if (isRotationLockedForCurrentPhase()) return null;
return target;
}
/**
@@ -1,6 +1,6 @@
package kamkeel.npcs.controllers.data.profile;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.sync.handlers.PlayerDataSyncHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
@@ -30,7 +30,7 @@ public class CNPCData implements IProfileData {
public void save(EntityPlayer player) {
PlayerData customNPCData = PlayerData.get(player);
customNPCData.save();
SyncController.syncPlayerData((EntityPlayerMP) player, false);
PlayerDataSyncHandler.syncPlayerData((EntityPlayerMP) player, false);
}
@Override
@@ -0,0 +1,167 @@
package kamkeel.npcs.controllers.sync;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import java.util.HashSet;
import java.util.Set;
/**
* Contract for a synchronized data type. Implementors handle both
* server-side serialization and client-side deserialization for their
* specific data type.
*
* <p>Each handler is registered with {@link SyncRegistry} and covers
* all three sync actions: RELOAD (full), UPDATE (single entity),
* and REMOVE (delete entity).</p>
*
* <p>Handlers that don't support UPDATE or REMOVE should use the
* default no-op implementations.</p>
*/
public interface SyncHandler {
// ========== SERVER-SIDE ==========
/**
* Serialize ALL objects of this type into an NBTTagCompound.
* This is the supplier for the cache system.
*
* <p>Called lazily when the cache is dirty and a player needs data.
* The returned compound is cached and chunked for transmission.</p>
*
* @return the serialized compound, or null if this type has no independent cache
*/
NBTTagCompound serializeAll();
// ========== CLIENT-SIDE ==========
/**
* Handle a RELOAD action on the client. Deserialize the full
* dataset and replace the client-side data.
*
* <p>Implementations should:
* <ol>
* <li>Deserialize from the compound into a sync buffer</li>
* <li>Atomically swap the sync buffer to the primary map</li>
* <li>Reset the sync buffer for the next reload</li>
* </ol>
*
* @param fullCompound the full serialized dataset from {@link #serializeAll()}
*/
@SideOnly(Side.CLIENT)
default void clientHandleReload(NBTTagCompound fullCompound){
// No-op: type does not support individual updates
}
/**
* Handle an UPDATE action on the client.
* Deserialize a single object and insert/replace it in the client-side data.
*
* <p>Default: no-op. Types that don't support individual updates
* use {@code syncAll()} for full reload instead.</p>
*
* @param compound the serialized single object
*/
@SideOnly(Side.CLIENT)
default void clientHandleUpdate(NBTTagCompound compound) {
// No-op: type does not support individual updates
}
/**
* Handle an UPDATE action on the client.
* Deserialize a single object and insert/replace it in the client-side data.
*
* <p>Default: no-op. Types that don't support individual updates
* use {@code syncAll()} for full reload instead.</p>
*
* @param compound the serialized single object
* @param categoryKey the parent category key (null if not applicable)
*/
@SideOnly(Side.CLIENT)
default void clientHandleUpdate(NBTTagCompound compound, String categoryKey) {
// No-op: type does not support individual updates
}
/**
* Handle an UPDATE action on the client. Deserialize a single
* entity and insert/replace it in the client-side data.
*
* <p>Default: no-op. Types that don't support individual updates
* use {@code syncAll()} for full reload instead.</p>
*
* @param compound the serialized single entity
* @param categoryId the parent category ID (-1 if not applicable)
*/
@SideOnly(Side.CLIENT)
default void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
// No-op: type does not support individual updates
}
/**
* Removes a single object from client-side data.
* Full object NBTTagCompound sent finer query control
* Int-keyed handlers should override {@link #clientHandleRemove(int)} instead.
*/
@SideOnly(Side.CLIENT)
default void clientHandleRemove(String key) {
}
/**
* Removes a single object with the given ID from client-side data.
*
* @param id the ID of the object to remove
*/
@SideOnly(Side.CLIENT)
default void clientHandleRemove(int id) {
}
/**
* Whether this handler supports the UPDATE action.
* Used for validation and self-documentation.
*/
default boolean supportsUpdate() {
return false;
}
/**
* Whether this handler supports the REMOVE action.
* Used for validation and self-documentation.
*/
default boolean supportsRemove() {
return false;
}
/**
* Whether this type should be included in login sync.
* Types that return true will be sent to players on login
* and checked for revision deltas on reconnect.
*
* <p>Default: true. Override to false for types like PLAYERDATA
* that are synced through separate mechanisms, or child types
* (DIALOG, QUEST) that share their parent's cache.</p>
*/
default boolean isCachedType() {
return true;
}
/**
* Get the set of cache types that must be invalidated when
* this type changes. Used for cascade invalidation.
*
* <p>Most types return just themselves. Parent-child types
* (e.g. DIALOG maps to DIALOG_CATEGORY) point children
* to the parent's cache.</p>
*
* @param self the SyncType this handler is registered under
* @return the set of types to invalidate
*/
default Set<SyncType> getInvalidationTargets(SyncType self) {
Set<SyncType> set = new HashSet<>();
set.add(self);
return set;
}
}
@@ -0,0 +1,69 @@
package kamkeel.npcs.controllers.sync;
import kamkeel.npcs.network.enums.SyncType;
import noppes.npcs.LogWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public final class SyncRegistry {
private static final LinkedHashMap<SyncType, SyncHandler> handlers = new LinkedHashMap<>();
private static SyncType[] loginTypesCache = null;
private SyncRegistry() {}
public static void register(SyncType type, SyncHandler handler) {
if (type == null) throw new IllegalArgumentException("SyncType must not be null");
if (handler == null) throw new IllegalArgumentException("SyncHandler must not be null for " + type);
if (handlers.containsKey(type)) throw new IllegalStateException("SyncHandler already registered for " + type);
handlers.put(type, handler);
loginTypesCache = null;
}
public static SyncHandler getHandler(SyncType type) {
return handlers.get(type);
}
public static SyncType[] getLoginTypes() {
if (loginTypesCache == null) {
List<SyncType> list = new ArrayList<>();
for (Map.Entry<SyncType, SyncHandler> e : handlers.entrySet())
if (e.getValue().isCachedType())
list.add(e.getKey());
loginTypesCache = list.toArray(new SyncType[0]);
}
return loginTypesCache;
}
public static Set<SyncType> getInvalidationTargets(SyncType type) {
SyncHandler handler = handlers.get(type);
if (handler == null) {
return Collections.emptySet();
}
return handler.getInvalidationTargets(type);
}
public static void clear() {
handlers.clear();
loginTypesCache = null;
}
public static boolean isRegistered(SyncType type) {
return handlers.containsKey(type);
}
public static Collection<SyncType> getRegisteredTypes() {
return Collections.unmodifiableCollection(handlers.keySet());
}
}
@@ -0,0 +1,56 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.RecipeController;
import noppes.npcs.controllers.data.RecipeAnvil;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#ANVIL_RECIPES}.
* RELOAD-only family — does not support individual UPDATE or REMOVE.
*/
public class AnvilRecipeSyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
RecipeController controller = RecipeController.Instance;
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (RecipeAnvil recipe : controller.anvilRecipes.values()) {
list.appendTag(recipe.writeNBT(false));
}
compound.setTag("recipes", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("recipes", 10);
if (list == null)
return;
for (int i = 0; i < list.tagCount(); i++) {
RecipeAnvil recipe = new RecipeAnvil();
recipe.readNBT(list.getCompoundTagAt(i));
RecipeController.syncAnvilRecipes.put(recipe.id, recipe);
}
RecipeController.Instance.anvilRecipes = RecipeController.syncAnvilRecipes;
RecipeController.syncAnvilRecipes = new HashMap<>();
}
// RELOAD-only: supportsUpdate() and supportsRemove() remain false (default)
}
@@ -0,0 +1,63 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.RecipeController;
import noppes.npcs.controllers.data.RecipeCarpentry;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#CARPENTRY_RECIPES}.
* RELOAD-only family — does not support individual UPDATE or REMOVE.
*/
public class CarpentryRecipeSyncHandler implements SyncHandler {
private static final CarpentryRecipeSyncHandler INSTANCE = new CarpentryRecipeSyncHandler();
public static CarpentryRecipeSyncHandler getInstance() {
return INSTANCE;
}
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
RecipeController controller = RecipeController.Instance;
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (RecipeCarpentry recipe : controller.carpentryRecipes.values()) {
list.appendTag(recipe.writeNBT(false));
}
compound.setTag("recipes", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("recipes", 10);
if (list == null)
return;
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound recipeCompound = list.getCompoundTagAt(i);
RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound);
recipe.readNBT(recipeCompound);
RecipeController.syncRecipes.put(recipe.id, recipe);
}
RecipeController.Instance.carpentryRecipes = RecipeController.syncRecipes;
RecipeController.syncRecipes = new HashMap<>();
}
// RELOAD-only: supportsUpdate() and supportsRemove() remain false (default)
}
@@ -0,0 +1,58 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Sync handler for {@link SyncType#CHAINED_ABILITY}.
* String-keyed family using ordered {@link LinkedHashMap} to preserve
* registration/reload order. Supports RELOAD only for global sync.
*/
public class ChainedAbilitySyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Map.Entry<String, ChainedAbility> entry : AbilityController.Instance.getChainedAbilities().entrySet()) {
NBTTagCompound chainNBT = entry.getValue().writeNBT(false);
chainNBT.setString("ChainedAbilityId", entry.getKey());
list.appendTag(chainNBT);
}
compound.setTag("Data", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("Data", 10);
LinkedHashMap<String, ChainedAbility> sync = new LinkedHashMap<>();
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound nbt = list.getCompoundTagAt(i);
String id = nbt.getString("ChainedAbilityId");
ChainedAbility chain = new ChainedAbility();
chain.readNBT(nbt);
chain.setName(id);
sync.put(id, chain);
}
AbilityController.Instance.setChainedAbilities(sync);
}
// RELOAD-only for global sync: supportsUpdate() and supportsRemove() remain false (default)
}
@@ -0,0 +1,59 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* Sync handler for {@link SyncType#CUSTOM_ABILITY}.
* String-keyed family using ordered {@link LinkedHashMap} to preserve
* registration/reload order. Supports RELOAD only for global sync.
*/
public class CustomAbilitySyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Map.Entry<String, Ability> entry : AbilityController.Instance.getCustomAbilities().entrySet()) {
NBTTagCompound abilityNBT = entry.getValue().writeNBT(false);
abilityNBT.setString("CustomAbilityId", entry.getKey());
list.appendTag(abilityNBT);
}
compound.setTag("Data", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("Data", 10);
LinkedHashMap<String, Ability> sync = new LinkedHashMap<>();
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound nbt = list.getCompoundTagAt(i);
String name = nbt.getString("CustomAbilityId");
Ability ability = AbilityController.Instance.fromNBT(nbt);
if (ability != null) {
ability.setName(name);
sync.put(name, ability);
}
}
AbilityController.Instance.setCustomAbilities(sync);
}
// RELOAD-only for global sync: supportsUpdate() and supportsRemove() remain false (default)
}
@@ -0,0 +1,82 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.controllers.data.CustomEffect;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#CUSTOM_EFFECTS}.
* Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support.
* Client-side RELOAD precaches effect icons via {@link ClientCacheHandler#getImageData}.
*/
public class CustomEffectSyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (CustomEffect effect : CustomEffectController.getInstance().getCustomEffects().values()) {
list.appendTag(effect.writeToNBT(false));
}
compound.setTag("Data", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("Data", 10);
CustomEffectController ce = CustomEffectController.getInstance();
ce.customEffectsSync.clear();
for (int i = 0; i < list.tagCount(); i++) {
CustomEffect effect = new CustomEffect();
effect.readFromNBT(list.getCompoundTagAt(i));
ClientCacheHandler.getImageData(effect.icon);
ce.customEffectsSync.put(effect.id, effect);
}
ce.getCustomEffects().clear();
ce.getCustomEffects().putAll(ce.customEffectsSync);
ce.customEffectsSync.clear();
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
CustomEffect effect = new CustomEffect();
effect.readFromNBT(compound);
ClientCacheHandler.getImageData(effect.icon);
CustomEffectController.Instance.getCustomEffects().put(effect.id, effect);
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
CustomEffectController.Instance.getCustomEffects().remove(id);
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
}
@@ -0,0 +1,140 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.DialogController;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.DialogCategory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#DIALOG_CATEGORY}.
* Parent-child category family. DIALOG children share this cache.
* Invalidation from DIALOG or DIALOG_CATEGORY both target this cache.
*/
public class DialogCategorySyncHandler implements SyncHandler {
/**
* Serialize a single dialog category for UPDATE packets.
*/
public static NBTTagCompound serializeCategory(DialogCategory dialogCategory) {
NBTTagCompound dialogCompound = new NBTTagCompound();
NBTTagList dialogList = new NBTTagList();
for (int questID : dialogCategory.dialogs.keySet()) {
Dialog dialog = dialogCategory.dialogs.get(questID);
dialogList.appendTag(dialog.writeToNBT(new NBTTagCompound()));
}
dialogCompound.setTag("Data", dialogList);
dialogCompound.setTag("CatNBT", dialogCategory.writeSmallNBT(new NBTTagCompound()));
return dialogCompound;
}
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagCompound compound = new NBTTagCompound();
NBTTagList categoryList = new NBTTagList();
for (DialogCategory category : DialogController.Instance.categories.values()) {
NBTTagCompound questCompound = new NBTTagCompound();
NBTTagList dialogList = new NBTTagList();
for (int dialogID : category.dialogs.keySet()) {
Dialog quest = category.dialogs.get(dialogID);
dialogList.appendTag(quest.writeToNBT(new NBTTagCompound()));
}
questCompound.setTag("Data", dialogList);
questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound()));
categoryList.appendTag(questCompound);
}
compound.setTag("DialogCategories", categoryList);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
if (!fullCompound.hasNoTags()) {
NBTTagList categories = fullCompound.getTagList("DialogCategories", 10);
for (int j = 0; j < fullCompound.getTagList("DialogCategories", 10).tagCount(); j++) {
NBTTagCompound categoryCompound = categories.getCompoundTagAt(j);
if (categoryCompound.hasNoTags())
continue;
DialogCategory category = new DialogCategory();
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
NBTTagList dialogList = categoryCompound.getTagList("Data", 10);
if (DialogController.Instance.categoriesSync.containsKey(category.id)) {
category = DialogController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < dialogList.tagCount(); i++) {
Dialog dialog = new Dialog();
dialog.readNBT(dialogList.getCompoundTagAt(i));
dialog.category = category;
category.dialogs.put(dialog.id, dialog);
}
DialogController.Instance.categoriesSync.put(category.id, category);
}
}
HashMap<Integer, Dialog> dialogs = new HashMap<>();
for (DialogCategory category : DialogController.Instance.categoriesSync.values()) {
for (Dialog dialog : category.dialogs.values()) {
dialogs.put(dialog.id, dialog);
}
}
DialogController.Instance.categories = DialogController.Instance.categoriesSync;
DialogController.Instance.dialogs = dialogs;
DialogController.Instance.categoriesSync = new HashMap<>();
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
DialogCategory category = new DialogCategory();
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
NBTTagList list = compound.getTagList("Data", 10);
if (DialogController.Instance.categoriesSync.containsKey(category.id)) {
category = DialogController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < list.tagCount(); i++) {
Dialog dialog = new Dialog();
dialog.readNBT(list.getCompoundTagAt(i));
dialog.category = category;
category.dialogs.put(dialog.id, dialog);
}
DialogController.Instance.categories.put(category.id, category);
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
DialogCategory dialogCategory = DialogController.Instance.categories.remove(id);
if (dialogCategory != null) {
DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet());
}
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
}
@@ -0,0 +1,89 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.DialogController;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.DialogCategory;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#DIALOG}.
* Child family — does not have its own cache. UPDATE and REMOVE only.
* Invalidation targets the parent {@link SyncType#DIALOG_CATEGORY} cache.
*/
public class DialogSyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
/**
* DIALOG does not have its own independent cache; it shares
* the DIALOG_CATEGORY parent cache.
*/
@Override
public NBTTagCompound serializeAll() {
return null;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
// DIALOG does not handle standalone RELOAD; it's part of DIALOG_CATEGORY
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
DialogCategory category = DialogController.Instance.categories.get(categoryId);
if (category == null) {
return; // Defensive: category may have been removed
}
Dialog dialog = new Dialog();
dialog.category = category;
dialog.readNBT(compound);
DialogController.Instance.dialogs.put(dialog.id, dialog);
category.dialogs.put(dialog.id, dialog);
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
Dialog dialog = DialogController.Instance.dialogs.remove(id);
if (dialog != null) {
dialog.category.dialogs.remove(id);
}
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
/**
* Not a cached type — DIALOG shares the DIALOG_CATEGORY cache.
*/
@Override
public boolean isCachedType() {
return false;
}
@Override
public Set<SyncType> getInvalidationTargets(SyncType self) {
// Child invalidates the parent cache
Set<SyncType> set = new HashSet<>();
set.add(SyncType.DIALOG_CATEGORY);
return set;
}
}
@@ -0,0 +1,76 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.FactionController;
import noppes.npcs.controllers.data.Faction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#FACTION}.
* Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support.
*/
public class FactionSyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Faction faction : FactionController.getInstance().factions.values()) {
NBTTagCompound factionNBT = new NBTTagCompound();
faction.writeNBT(factionNBT);
list.appendTag(factionNBT);
}
compound.setTag("Factions", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("Factions", 10);
for (int i = 0; i < list.tagCount(); i++) {
Faction faction = new Faction();
faction.readNBT(list.getCompoundTagAt(i));
FactionController.getInstance().factionsSync.put(faction.id, faction);
}
FactionController.getInstance().factions = FactionController.getInstance().factionsSync;
FactionController.getInstance().factionsSync = new HashMap<Integer, Faction>();
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
Faction faction = new Faction();
faction.readNBT(compound);
FactionController.getInstance().factions.put(faction.id, faction);
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
FactionController.getInstance().factions.remove(id);
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
}
@@ -0,0 +1,79 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.MagicController;
import noppes.npcs.controllers.data.MagicCycle;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#MAGIC_CYCLE}.
* Simple int-keyed map family with RELOAD, UPDATE, and REMOVE support.
*/
public class MagicCycleSyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
NBTTagCompound cycleCompound = new NBTTagCompound();
cycle.writeNBT(cycleCompound);
list.appendTag(cycleCompound);
}
compound.setTag("Data", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("Data", 10);
MagicController mc = MagicController.getInstance();
mc.cyclesSync.clear();
for (int i = 0; i < list.tagCount(); i++) {
MagicCycle cycle = new MagicCycle();
cycle.readNBT(list.getCompoundTagAt(i));
mc.cyclesSync.put(cycle.id, cycle);
}
mc.cycles.clear();
mc.cycles.putAll(mc.cyclesSync);
mc.cyclesSync.clear();
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
MagicCycle cycle = new MagicCycle();
cycle.readNBT(compound);
MagicController.getInstance().cycles.put(cycle.id, cycle);
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
MagicController.getInstance().cycles.remove(id);
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
}
@@ -0,0 +1,95 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.MagicController;
import noppes.npcs.controllers.data.Magic;
import noppes.npcs.controllers.data.MagicCycle;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#MAGIC}.
* Simple int-keyed map family.
* REMOVE dissociates cycle associations before removing the magic entry.
*
* <p>Note: The original code had a bug where MAGIC REMOVE incorrectly
* removed from {@code cycles} instead of {@code magics}. This handler
* fixes that by properly removing from {@code magics} after dissociating.</p>
*/
public class MagicSyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (Magic magic : MagicController.getInstance().magics.values()) {
NBTTagCompound magicCompound = new NBTTagCompound();
magic.writeNBT(magicCompound);
list.appendTag(magicCompound);
}
compound.setTag("Data", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("Data", 10);
MagicController mc = MagicController.getInstance();
mc.magicSync.clear();
for (int i = 0; i < list.tagCount(); i++) {
Magic magic = new Magic();
magic.readNBT(list.getCompoundTagAt(i));
mc.magicSync.put(magic.id, magic);
}
mc.magics.clear();
mc.magics.putAll(mc.magicSync);
mc.magicSync.clear();
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
Magic magic = new Magic();
magic.readNBT(compound);
MagicController.getInstance().magics.put(magic.id, magic);
}
/**
* Removes a magic entry from the client. First dissociates cycle
* references, then removes from the magics map.
* <p>Bug fix: The original code incorrectly removed from {@code cycles}
* instead of {@code magics} after dissociating cycle associations.</p>
*/
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
// First remove this magic's association from all cycles
for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
cycle.associations.remove(id);
}
// Then remove the magic itself (fixed: was cycles.remove(id))
MagicController.getInstance().magics.remove(id);
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
}
@@ -0,0 +1,47 @@
package kamkeel.npcs.controllers.sync.handlers;
import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket;
import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket;
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.controllers.data.PlayerData;
/**
* Direct per-player sync helper for player ability state.
* This is NOT a cached global sync family — it operates outside the
* registry-driven reload/revision system.
*
* <p>Abilities are synced per-player on demand (e.g. ability unlock,
* entity reconstruction, periodic cooldown ticks).</p>
*/
public final class PlayerAbilitySyncHelper {
private PlayerAbilitySyncHelper() {
}
/**
* Full sync of all player ability state to the client: unlocked abilities,
* selection, toggles, hotbar layout, and cooldowns.
* Used for entity reconstruction and other full-refresh scenarios.
*/
public static void syncAbilities(EntityPlayerMP playerMP) {
PlayerData playerData = PlayerData.get(playerMP);
if (playerData == null) return;
PlayerAbilitySyncPacket.sendToPlayer(playerMP);
AbilityHotbarSyncPacket.sendToPlayer(playerMP);
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
}
/**
* Lightweight sync of cooldown state only (global + per-ability).
* Called periodically (every 10 ticks) to keep the client's cooldown
* display accurate. Cooldowns are transient and not part of NBT sync.
*/
public static void syncAbilityCooldowns(EntityPlayerMP playerMP) {
PlayerData playerData = PlayerData.get(playerMP);
if (playerData == null) return;
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
}
}
@@ -0,0 +1,55 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.ClientCacheHandler;
import noppes.npcs.controllers.data.PlayerData;
/**
* Sync handler for {@link SyncType#PLAYERDATA}.
* Special non-cached per-player path. Not included in login cache iteration.
* RELOAD and UPDATE are sent as direct per-player packets.
*/
public class PlayerDataSyncHandler implements SyncHandler {
public static void syncPlayerData(EntityPlayerMP player, boolean update) {
PlayerData data = PlayerData.get(player);
if (data != null)
SyncController.syncPlayerData(SyncType.PLAYERDATA, update ? data.getSyncNBTFull() : data.getSyncNBT(), update, player);
}
// ========== SERVER-SIDE ==========
/**
* PLAYERDATA is not a global cached type — it is per-player.
*/
@Override
public NBTTagCompound serializeAll() {
return null;
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
if (categoryId == 1) ClientCacheHandler.playerData.setSyncNBTFull(compound);
else ClientCacheHandler.playerData.setSyncNBT(compound);
}
@Override
public boolean supportsUpdate() {
return true;
}
/**
* Not a cached type — PLAYERDATA uses direct per-player sync.
*/
@Override
public boolean isCachedType() {
return false;
}
}
@@ -0,0 +1,54 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.data.large.SyncEffectPacket;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.CustomEffectController;
import noppes.npcs.controllers.data.EffectKey;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.PlayerEffect;
import java.util.concurrent.ConcurrentHashMap;
/**
* Direct per-player sync helper for player effects.
* This is NOT a cached global sync family — it operates outside the
* registry-driven reload/revision system.
*
* <p>Effects are synced per-player on demand (e.g. effect application,
* periodic ticks). The data mutates {@code playerData.effectData}
* before sending the packet.</p>
*/
public final class PlayerEffectSyncHelper {
private PlayerEffectSyncHelper() {
}
/**
* Server-side: sync the player's active effects to their client.
* Mutates {@code playerData.effectData} before sending.
*/
public static void syncEffects(EntityPlayerMP playerMP) {
ConcurrentHashMap<EffectKey, PlayerEffect> playerEffects = CustomEffectController.getInstance().getPlayerEffects(playerMP);
PlayerData playerData = PlayerData.get(playerMP);
playerData.effectData.setEffects(playerEffects);
NBTTagCompound compound = playerData.getPlayerEffects();
PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP);
}
/**
* Client-side: apply incoming effect data to the local player.
*/
@SideOnly(Side.CLIENT)
public static void clientSyncEffects(NBTTagCompound compound) {
PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer);
if (playerData != null) {
playerData.setPlayerEffects(compound);
}
}
}
@@ -0,0 +1,141 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.controllers.data.QuestCategory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#QUEST_CATEGORY}.
* Parent-child category family. QUEST children share this cache.
* Invalidation from QUEST or QUEST_CATEGORY both target this cache.
*/
public class QuestCategorySyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
NBTTagCompound compound = new NBTTagCompound();
NBTTagList categoryList = new NBTTagList();
for (QuestCategory category : QuestController.Instance.categories.values()) {
NBTTagCompound questCompound = new NBTTagCompound();
;
NBTTagList questList = new NBTTagList();
for (int questID : category.quests.keySet()) {
Quest quest = category.quests.get(questID);
questList.appendTag(quest.writeToNBT(new NBTTagCompound()));
}
questCompound.setTag("Data", questList);
questCompound.setTag("CatNBT", category.writeSmallNBT(new NBTTagCompound()));
categoryList.appendTag(questCompound);
}
compound.setTag("QuestCategories", categoryList);
return compound;
}
/**
* Serialize a single quest category for UPDATE packets.
*/
public static NBTTagCompound serializeCategory(QuestCategory questCategory) {
NBTTagCompound questCompound = new NBTTagCompound();
NBTTagList questList = new NBTTagList();
for (int questID : questCategory.quests.keySet()) {
Quest quest = questCategory.quests.get(questID);
questList.appendTag(quest.writeToNBT(new NBTTagCompound()));
}
questCompound.setTag("Data", questList);
questCompound.setTag("CatNBT", questCategory.writeSmallNBT(new NBTTagCompound()));
return questCompound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
if (!fullCompound.hasNoTags()) {
NBTTagList categories = fullCompound.getTagList("QuestCategories", 10);
for (int j = 0; j < fullCompound.getTagList("QuestCategories", 10).tagCount(); j++) {
NBTTagCompound categoryCompound = categories.getCompoundTagAt(j);
if (categoryCompound.hasNoTags())
continue;
QuestCategory category = new QuestCategory();
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
NBTTagList questList = categoryCompound.getTagList("Data", 10);
if (QuestController.Instance.categoriesSync.containsKey(category.id)) {
category = QuestController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(categoryCompound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < questList.tagCount(); i++) {
Quest quest = new Quest();
quest.readNBT(questList.getCompoundTagAt(i));
quest.category = category;
category.quests.put(quest.id, quest);
}
QuestController.Instance.categoriesSync.put(category.id, category);
}
}
HashMap<Integer, Quest> quests = new HashMap<>();
for (QuestCategory category : QuestController.Instance.categoriesSync.values()) {
for (Quest quest : category.quests.values()) {
quests.put(quest.id, quest);
}
}
QuestController.Instance.categories = QuestController.Instance.categoriesSync;
QuestController.Instance.quests = quests;
QuestController.Instance.categoriesSync = new HashMap<>();
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
QuestCategory category = new QuestCategory();
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
NBTTagList list = compound.getTagList("Data", 10);
if (QuestController.Instance.categoriesSync.containsKey(category.id)) {
category = QuestController.Instance.categoriesSync.get(category.id);
category.readSmallNBT(compound.getCompoundTag("CatNBT"));
}
for (int i = 0; i < list.tagCount(); i++) {
Quest quest = new Quest();
quest.readNBT(list.getCompoundTagAt(i));
quest.category = category;
category.quests.put(quest.id, quest);
}
QuestController.Instance.categories.put(category.id, category);
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
QuestCategory questCategory = QuestController.Instance.categories.remove(id);
if (questCategory != null) {
QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet());
}
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
}
@@ -0,0 +1,90 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.controllers.QuestController;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.controllers.data.QuestCategory;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#QUEST}.
* Child family — does not have its own cache. UPDATE and REMOVE only.
* Invalidation targets the parent {@link SyncType#QUEST_CATEGORY} cache.
*/
public class QuestSyncHandler implements SyncHandler {
// ========== SERVER-SIDE ==========
/**
* QUEST does not have its own independent cache; it shares
* the QUEST_CATEGORY parent cache.
*/
@Override
public NBTTagCompound serializeAll() {
return null;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
// QUEST does not handle standalone RELOAD; it's part of QUEST_CATEGORY
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleUpdate(NBTTagCompound compound, int categoryId) {
QuestCategory category = QuestController.Instance.categories.get(categoryId);
if (category == null)
return; // Defensive: category may have been removed
Quest quest = new Quest();
quest.category = category;
quest.readNBT(compound);
QuestController.Instance.quests.put(quest.id, quest);
category.quests.put(quest.id, quest);
}
@SideOnly(Side.CLIENT)
@Override
public void clientHandleRemove(int id) {
Quest quest = QuestController.Instance.quests.remove(id);
if (quest != null)
quest.category.quests.remove(id);
}
@Override
public boolean supportsUpdate() {
return true;
}
@Override
public boolean supportsRemove() {
return true;
}
/**
* Not a cached type — QUEST shares the QUEST_CATEGORY cache.
*/
@Override
public boolean isCachedType() {
return false;
}
@Override
public Set<SyncType> getInvalidationTargets(SyncType self) {
// Child invalidates the parent cache
Set<SyncType> set = new HashSet<>();
set.add(SyncType.QUEST_CATEGORY);
return set;
}
}
@@ -0,0 +1,70 @@
package kamkeel.npcs.controllers.sync.handlers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.sync.SyncHandler;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.RecipeController;
import noppes.npcs.controllers.data.RecipeCarpentry;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Sync handler for {@link SyncType#WORKBENCH_RECIPES}.
* RELOAD-only family — does not support individual UPDATE or REMOVE.
* Client-side RELOAD routes through {@link RecipeController#reloadGlobalRecipes}.
*/
public class WorkbenchRecipeSyncHandler implements SyncHandler {
private static final WorkbenchRecipeSyncHandler INSTANCE = new WorkbenchRecipeSyncHandler();
public static WorkbenchRecipeSyncHandler getInstance() {
return INSTANCE;
}
// ========== SERVER-SIDE ==========
@Override
public NBTTagCompound serializeAll() {
RecipeController controller = RecipeController.Instance;
NBTTagList list = new NBTTagList();
NBTTagCompound compound = new NBTTagCompound();
for (RecipeCarpentry recipe : controller.globalRecipes.values()) {
list.appendTag(recipe.writeNBT(false));
}
compound.setTag("recipes", list);
return compound;
}
// ========== CLIENT-SIDE ==========
@SideOnly(Side.CLIENT)
@Override
public void clientHandleReload(NBTTagCompound fullCompound) {
NBTTagList list = fullCompound.getTagList("recipes", 10);
if (list == null)
return;
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound recipeCompound = list.getCompoundTagAt(i);
RecipeCarpentry recipe = RecipeCarpentry.create(recipeCompound);
recipe.readNBT(recipeCompound);
RecipeController.syncRecipes.put(recipe.id, recipe);
}
RecipeController.reloadGlobalRecipes(RecipeController.syncRecipes);
RecipeController.syncRecipes = new HashMap<>();
}
@Override
public Set<SyncType> getInvalidationTargets(SyncType self) {
Set<SyncType> set = new HashSet<>();
set.add(SyncType.WORKBENCH_RECIPES);
return set;
}
// RELOAD-only: supportsUpdate() and supportsRemove() remain false (default)
}
@@ -264,18 +264,18 @@ public class EntityAbilityLaser extends EntityEnergyProjectile {
Vec3 anchorPos = AnchorPointHelper.calculateAnchorPosition(livingOwner, anchorData);
setPosition(anchorPos.xCoord, anchorPos.yCoord, anchorPos.zCoord);
Entity targetEntity = getTargetEntity();
if (targetEntity instanceof EntityLivingBase && targetEntity.isEntityAlive()) {
EntityLivingBase target = (EntityLivingBase) targetEntity;
double dx = target.posX - anchorPos.xCoord;
double dy = (target.posY + target.getEyeHeight() - 0.4) - anchorPos.yCoord;
double dz = target.posZ - anchorPos.zCoord;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0.0001) {
dirX = dx / len;
dirY = dy / len;
dirZ = dz / len;
}
// Aim where the owner is looking so track speed and rotation lock still apply.
double aimX = livingOwner.posX + dirX * maxLength;
double aimY = livingOwner.posY + livingOwner.getEyeHeight() + dirY * maxLength;
double aimZ = livingOwner.posZ + dirZ * maxLength;
double dx = aimX - anchorPos.xCoord;
double dy = aimY - anchorPos.yCoord;
double dz = aimZ - anchorPos.zCoord;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len > 0.0001) {
dirX = dx / len;
dirY = dy / len;
dirZ = dz / len;
}
} else {
Vec3 direction = Vec3.createVectorHelper(dirX, dirY, dirZ);
@@ -155,6 +155,8 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
// HAZARD-SPECIFIC PROPERTIES
// ═══════════════════════════════════════════════════════════════════
public static final int MIN_DAMAGE_INTERVAL = 5;
private float damagePerSecond = 1.0f;
private int damageInterval = 20;
private boolean ignoreIFrames = false;
@@ -291,7 +293,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
zone.shape = shape;
zone.radius = radius;
zone.damagePerSecond = damagePerSecond;
zone.damageInterval = damageInterval;
zone.damageInterval = Math.max(MIN_DAMAGE_INTERVAL, damageInterval);
zone.ignoreIFrames = ignoreIFrames;
zone.affectsCaster = affectsCaster;
zone.durationTicks = durationTicks;
@@ -309,7 +311,6 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
zone.effects.add(e.copy());
}
}
zone.ticksSinceDamage = damageInterval;
return zone;
}
@@ -518,7 +519,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
if (!isInZone(entity)) continue;
if (damagePerSecond > 0) {
applyDamage(entity, owner, damagePerSecond);
applyDamage(entity, owner, damagePerSecond * (damageInterval / 20.0f));
}
applyEffects(entity);
@@ -815,7 +816,7 @@ public class EntityAbilityZone extends Entity implements IEntityAdditionalSpawnD
public float getDamagePerSecond() { return damagePerSecond; }
public void setDamagePerSecond(float dps) { this.damagePerSecond = dps; }
public int getDamageInterval() { return damageInterval; }
public void setDamageInterval(int ticks) { this.damageInterval = ticks; }
public void setDamageInterval(int ticks) { this.damageInterval = Math.max(MIN_DAMAGE_INTERVAL, ticks); }
public boolean isAffectsCaster() { return affectsCaster; }
public void setAffectsCaster(boolean affects) { this.affectsCaster = affects; }
@@ -1,5 +1,7 @@
package kamkeel.npcs.entity;
import kamkeel.npcs.addon.DBCAddon;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.util.AbilityTargetHelper;
import kamkeel.npcs.controllers.data.ability.data.energy.EnergyBarrierData;
import kamkeel.npcs.network.packets.data.energy.BarrierClientSyncPacket;
@@ -15,6 +17,7 @@ import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import noppes.npcs.CustomNpcs;
import noppes.npcs.EventHooks;
import noppes.npcs.config.ConfigMain;
import noppes.npcs.controllers.data.MagicData;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.entity.EntityNPCInterface;
@@ -114,6 +117,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
protected EnergyBarrierData barrierData = new EnergyBarrierData();
protected float currentHealth;
protected int ticksAlive = 0;
protected long barrierDeathTime = -1;
// ==================== DATA WATCHER INDICES ====================
protected static final int DW_HEALTH_PERCENT = 21;
@@ -436,8 +440,17 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
float damage = amount * barrierData.meleeDamageMultiplier;
// Apply magic interactions from attacker's magic vs barrier's magic
Entity attacker = source.getEntity();
// No LivingHurtEvent fires for a barrier, so scale the hit here.
if (attacker instanceof EntityLivingBase) {
damage = AbilityController.Instance.fireModifyBarrierMeleeDamage(this, (EntityLivingBase) attacker, damage);
}
if (attacker instanceof EntityPlayer && ConfigMain.AttributesEnabled && !DBCAddon.IsAvailable()) {
damage = AttributeAttackUtil.calculateOutgoing((EntityPlayer) attacker, damage);
}
// Apply magic interactions from attacker's magic vs barrier's magic
if (attacker != null) {
MagicData attackerMagic = null;
if (attacker instanceof EntityPlayer) {
@@ -510,15 +523,13 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
}
}
// Duration check
if (barrierData.useDuration && ticksAlive >= barrierData.durationTicks) {
onBarrierDestroyed();
this.setDead();
return true;
if (barrierDeathTime < 0 && !isCharging()) {
barrierDeathTime = worldObj.getTotalWorldTime()
+ (barrierData.useDuration ? barrierData.durationTicks : BARRIER_HARD_LIFETIME_CAP);
}
// Absolute hard lifetime cap (safety net for barriers with no duration)
if (ticksAlive > BARRIER_HARD_LIFETIME_CAP) {
// Duration check
if (barrierDeathTime >= 0 && worldObj.getTotalWorldTime() >= barrierDeathTime) {
onBarrierDestroyed();
this.setDead();
return true;
@@ -865,6 +876,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
protected void writeBarrierBaseNBT(NBTTagCompound nbt) {
writeEnergyBaseNBT(nbt);
nbt.setInteger("TicksAlive", ticksAlive);
nbt.setLong("BarrierDeathTime", barrierDeathTime);
nbt.setFloat("CurrentHealth", currentHealth);
nbt.setBoolean("Charging", charging);
nbt.setInteger("ChargeTick", chargeTick);
@@ -879,6 +891,7 @@ public abstract class EntityEnergyBarrier extends EntityEnergyAbility {
protected void readBarrierBaseNBT(NBTTagCompound nbt) {
readEnergyBaseNBT(nbt);
this.ticksAlive = nbt.getInteger("TicksAlive");
this.barrierDeathTime = nbt.hasKey("BarrierDeathTime") ? nbt.getLong("BarrierDeathTime") : -1;
this.currentHealth = nbt.getFloat("CurrentHealth");
if (Float.isNaN(currentHealth) || Float.isInfinite(currentHealth) || currentHealth < 0) currentHealth = barrierData.maxHealth;
this.charging = nbt.hasKey("Charging") && nbt.getBoolean("Charging");
@@ -911,42 +911,17 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
@Override
public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements) {
int steps = Math.max(1, posRotationIncrements);
double dx = x - this.posX;
double dy = y - this.posY;
double dz = z - this.posZ;
double dotToCurrentMotion = dx * this.motionX + dy * this.motionY + dz * this.motionZ;
// Spawn-time and large correction snaps: avoid visible startup rubber-banding.
if (worldObj != null && worldObj.isRemote) {
double distSq = dx * dx + dy * dy + dz * dz;
// Launch-time stale tracker packets can arrive one update late and point behind
// an already-predicted projectile. Skipping these avoids visible backward "bounce".
if (ticksExisted <= 24 && distSq <= 4.0D && dotToCurrentMotion < -0.0025D) {
return;
}
if (ticksExisted <= 2 || distSq > 16.0D) {
this.setPosition(x, y, z);
syncPositionState(x, y, z, true);
return;
}
}
this.interpTargetX = x;
this.interpTargetY = y;
this.interpTargetZ = z;
if (worldObj != null && worldObj.isRemote && ticksExisted <= 24 && dotToCurrentMotion < 0.0D) {
// Keep existing velocity when correction points opposite current travel
// to prevent launch-time reverse lerp.
this.interpTargetMotionX = this.motionX;
this.interpTargetMotionY = this.motionY;
this.interpTargetMotionZ = this.motionZ;
} else {
this.interpTargetMotionX = dx / steps;
this.interpTargetMotionY = dy / steps;
this.interpTargetMotionZ = dz / steps;
}
this.interpSteps = steps;
this.rotationYaw = yaw;
this.rotationPitch = pitch;
// Energy projectiles are tracked every tick. Minecraft's usual three-tick
// interpolation continually falls behind that update rate at higher speeds.
// One tick still gives RenderManager a full partial-tick transition without
// accumulating a correction that later has to snap.
this.interpSteps = 1;
}
@Override
@@ -959,14 +934,7 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
this.motionZ = motionZ;
}
/**
* Handle client-side position interpolation.
* Only moves position during active interpolation (interpSteps > 0).
* Does NOT predict/drift between server updates — the motion values are
* derived from correction deltas, not actual entity velocity, so applying
* them between updates causes entities to fly off in wrong directions.
* This matches vanilla Minecraft behavior for non-player entities.
*/
/** Move the client copy through the latest server position update. */
protected void handleClientInterpolation() {
if (this.interpSteps > 0) {
double dx = this.interpTargetX - this.posX;
@@ -984,10 +952,6 @@ public abstract class EntityEnergyProjectile extends EntityEnergyAbility {
double newY = this.posY + dy / this.interpSteps;
double newZ = this.posZ + dz / this.interpSteps;
this.motionX = this.motionX + (this.interpTargetMotionX - this.motionX) / this.interpSteps;
this.motionY = this.motionY + (this.interpTargetMotionY - this.motionY) / this.interpSteps;
this.motionZ = this.motionZ + (this.interpTargetMotionZ - this.motionZ) / this.interpSteps;
this.setPosition(newX, newY, newZ);
this.interpSteps--;
}
@@ -1,18 +0,0 @@
package kamkeel.npcs.network.enums;
public enum EnumSyncType {
FACTION,
DIALOG,
DIALOG_CATEGORY,
QUEST,
QUEST_CATEGORY,
PLAYERDATA,
MAGIC,
MAGIC_CYCLE,
WORKBENCH_RECIPES,
CARPENTRY_RECIPES,
ANVIL_RECIPES,
CUSTOM_EFFECTS,
CUSTOM_ABILITY,
CHAINED_ABILITY
}
@@ -0,0 +1,142 @@
package kamkeel.npcs.network.enums;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Immutable, object-based sync-type identity for the CNPC+ sync backend.
*
* <p>Each {@code SyncType} has a canonical namespaced string ID ({@code modid:path})
* and is registered via the static {@link #register} factory. Built-in CNPC+
* families are exposed as {@code public static final} constants.</p>
*
* <p>Identity is based on the canonical {@link #id} string, which is unique
* across all registered types. Two references with the same {@code id}
* are always the same object (identity == equality for registered types).</p>
*
* <p>The {@code ordinal} field provides a stable integer identity for
* wire encoding during the migration period. It is assigned at registration
* time in declaration order and must NOT be used as a protocol identifier
* once string-on-wire migration is complete.</p>
*/
public final class SyncType {
// ──────────────────── Registry ────────────────────
private static final Map<String, SyncType> REGISTRY = new LinkedHashMap<>();
private static int nextOrdinal = 0;
// ──────────────────── CNPC+ families ────────────────────
public static final SyncType FACTION = register("cnpc:faction");
public static final SyncType DIALOG = register("cnpc:dialog");
public static final SyncType DIALOG_CATEGORY = register("cnpc:dialog_category");
public static final SyncType QUEST = register("cnpc:quest");
public static final SyncType QUEST_CATEGORY = register("cnpc:quest_category");
public static final SyncType PLAYERDATA = register("cnpc:playerdata");
public static final SyncType MAGIC = register("cnpc:magic");
public static final SyncType MAGIC_CYCLE = register("cnpc:magic_cycle");
public static final SyncType WORKBENCH_RECIPES = register("cnpc:workbench_recipes");
public static final SyncType CARPENTRY_RECIPES = register("cnpc:carpentry_recipes");
public static final SyncType ANVIL_RECIPES = register("cnpc:anvil_recipes");
public static final SyncType CUSTOM_EFFECTS = register("cnpc:custom_effects");
public static final SyncType CUSTOM_ABILITY = register("cnpc:custom_ability");
public static final SyncType CHAINED_ABILITY = register("cnpc:chained_ability");
// ──────────────────── Instance fields ────────────────────
private final String id;
private final int ordinal;
private SyncType(String id, int ordinal) {
this.id = id;
this.ordinal = ordinal;
}
// ──────────────────── Public API ────────────────────
/**
* The canonical namespaced identifier, e.g. {@code "cnpc:faction"}.
*/
public String getId() {
return id;
}
/**
* Stable integer ordinal assigned at registration time.
* Used for wire encoding during the migration period only.
*/
public int ordinal() {
return ordinal;
}
// ──────────────────── Registration ────────────────────
/**
* Register a new {@code SyncType} with the given canonical ID.
*
* @param id namespaced identifier ({@code modid:path})
* @return the newly created and registered {@code SyncType}
* @throws IllegalArgumentException if the ID is null, empty, or lacks a colon
* @throws IllegalStateException if a type with the same ID is already registered
* @throws IllegalStateException if the registry has been frozen
*/
public static SyncType register(String id) {
if (id == null || id.isEmpty()) throw new IllegalArgumentException("SyncType id must not be null or empty");
if (!id.contains(":")) throw new IllegalArgumentException("SyncType id must be namespaced (modid:path): " + id);
if (REGISTRY.containsKey(id)) throw new IllegalStateException("Duplicate SyncType registration: " + id);
SyncType type = new SyncType(id, nextOrdinal++);
REGISTRY.put(id, type);
return type;
}
/**
* Look up a registered SyncType by its canonical string ID.
*
* @return the registered type, or {@code null} if not found
*/
public static SyncType byId(String id) {
return id == null ? null : REGISTRY.get(id);
}
/**
* Look up a registered SyncType by its ordinal.
* Used during migration for decoding ordinal-based wire traffic.
*
* @return the registered type, or {@code null} if ordinal is out of range
*/
public static SyncType byOrdinal(int ordinal) {
if (ordinal < 0) return null;
for (SyncType type : REGISTRY.values())
if (type.ordinal == ordinal) return type;
return null;
}
/**
* Returns all registered SyncType instances in registration order.
*/
public static Collection<SyncType> values() {
return Collections.unmodifiableCollection(REGISTRY.values());
}
// ──────────────────── Object overrides ────────────────────
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SyncType)) return false;
return id.equals(((SyncType) o).id);
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public String toString() {
return id;
}
}
@@ -8,7 +8,7 @@ import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketClient;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumDataPacket;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.player.SyncRevisionInfoPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
@@ -21,19 +21,20 @@ import noppes.npcs.controllers.AuctionConfigSync;
import noppes.npcs.controllers.ScriptConfigSync;
import java.io.IOException;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public final class LoginPacket extends AbstractPacket {
public static final String packetName = "CNPC+|Login";
private String serverCacheKey = "";
private final EnumMap<EnumSyncType, Integer> revisionSnapshot = new EnumMap<>(EnumSyncType.class);
private final Map<SyncType, Integer> revisionSnapshot = new LinkedHashMap<>();
public LoginPacket() {
}
public LoginPacket(String serverCacheKey, EnumMap<EnumSyncType, Integer> revisionSnapshot) {
public LoginPacket(String serverCacheKey, Map<SyncType, Integer> revisionSnapshot) {
if (serverCacheKey != null) {
this.serverCacheKey = serverCacheKey;
}
@@ -58,17 +59,15 @@ public final class LoginPacket extends AbstractPacket {
out.writeBoolean(ConfigMain.ProfilesEnabled);
ByteBufUtils.writeString(out, serverCacheKey);
out.writeShort(revisionSnapshot.size());
for (Map.Entry<EnumSyncType, Integer> entry : revisionSnapshot.entrySet()) {
for (Map.Entry<SyncType, Integer> entry : revisionSnapshot.entrySet()) {
out.writeInt(entry.getKey().ordinal());
out.writeInt(entry.getValue());
}
// Send auction config (server-side sync)
NBTTagCompound auctionConfig = new NBTTagCompound();
AuctionConfigSync.writeToNBT(auctionConfig);
ByteBufUtils.writeNBT(out, auctionConfig);
// Send script config (server-side sync)
NBTTagCompound scriptConfig = new NBTTagCompound();
ScriptConfigSync.writeToNBT(scriptConfig);
ByteBufUtils.writeNBT(out, scriptConfig);
@@ -82,20 +81,20 @@ public final class LoginPacket extends AbstractPacket {
String serverKey = ByteBufUtils.readString(in);
int revisionCount = in.readUnsignedShort();
EnumMap<EnumSyncType, Integer> serverRevisions = new EnumMap<>(EnumSyncType.class);
Map<SyncType, Integer> serverRevisions = new LinkedHashMap<>();
for (int i = 0; i < revisionCount; i++) {
EnumSyncType type = EnumSyncType.values()[in.readInt()];
SyncType type = SyncType.byOrdinal(in.readInt());
int revision = in.readInt();
serverRevisions.put(type, revision);
if (type != null) {
serverRevisions.put(type, revision);
}
}
ClientCacheHandler.setActiveServer(serverKey, serverRevisions);
// Read auction config
NBTTagCompound auctionConfig = ByteBufUtils.readNBT(in);
AuctionClientConfig.readFromNBT(auctionConfig);
// Read script config
NBTTagCompound scriptConfig = ByteBufUtils.readNBT(in);
ScriptClientConfig.readFromNBT(scriptConfig);
@@ -8,24 +8,24 @@ import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.NoppesUtil;
import java.io.IOException;
import java.util.UUID;
public final class PlayerUpdateSkinOverlaysPacket extends AbstractPacket {
public static final String packetName = "Data|PlayerUpdateSkinOverlays";
private String playerName;
private String playerUUID;
private NBTTagCompound compound;
public PlayerUpdateSkinOverlaysPacket() {
}
public PlayerUpdateSkinOverlaysPacket(String playerName, NBTTagCompound compound) {
this.playerName = playerName;
public PlayerUpdateSkinOverlaysPacket(UUID playerUUID, NBTTagCompound compound) {
this.playerUUID = playerUUID == null ? "" : playerUUID.toString();
this.compound = compound;
}
@@ -41,18 +41,21 @@ public final class PlayerUpdateSkinOverlaysPacket extends AbstractPacket {
@Override
public void sendData(ByteBuf out) throws IOException {
ByteBufUtils.writeString(out, this.playerName);
ByteBufUtils.writeString(out, this.playerUUID);
ByteBufUtils.writeNBT(out, this.compound);
}
@SideOnly(Side.CLIENT)
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
String playerName = ByteBufUtils.readString(in);
String uuid = ByteBufUtils.readString(in);
NBTTagCompound nbt = ByteBufUtils.readNBT(in);
EntityPlayer sendingPlayer = Minecraft.getMinecraft().theWorld.getPlayerEntityByName(playerName);
if (sendingPlayer != null) {
NoppesUtil.updateSkinOverlayData(sendingPlayer, nbt);
if (uuid == null || uuid.isEmpty())
return;
try {
NoppesUtil.updateSkinOverlayData(UUID.fromString(uuid), nbt);
} catch (IllegalArgumentException ignored) {
}
}
}
@@ -9,13 +9,9 @@ import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumDataPacket;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.client.gui.util.GuiContainerNPCInterface;
import noppes.npcs.client.gui.util.GuiNPCInterface;
import noppes.npcs.client.gui.util.IGuiData;
import java.io.IOException;
@@ -59,15 +55,6 @@ public final class GuiDataPacket extends LargeAbstractPacket {
@SideOnly(Side.CLIENT)
@Override
protected void handleCompleteData(ByteBuf data, EntityPlayer player) throws IOException {
GuiScreen gui = Minecraft.getMinecraft().currentScreen;
if (gui instanceof GuiNPCInterface && ((GuiNPCInterface) gui).hasSubGui()) {
gui = ((GuiNPCInterface) gui).getSubGui();
} else if (gui instanceof GuiContainerNPCInterface && ((GuiContainerNPCInterface) gui).hasSubGui()) {
gui = ((GuiContainerNPCInterface) gui).getSubGui();
}
if (gui instanceof IGuiData) {
NBTTagCompound nbt = ByteBufUtils.readBigNBT(data);
((IGuiData) gui).setGuiData(nbt);
}
IGuiData.legacySetGuiData(ByteBufUtils.readBigNBT(data));
}
}
@@ -4,7 +4,7 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper;
import kamkeel.npcs.network.LargeAbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
@@ -54,7 +54,7 @@ public final class SyncEffectPacket extends LargeAbstractPacket {
return;
try {
NBTTagCompound tag = ByteBufUtils.readBigNBT(data);
SyncController.clientSyncEffects(tag);
PlayerEffectSyncHelper.clientSyncEffects(tag);
} catch (RuntimeException e) {
LogWriter.error(String.format("Attempted to Sync Effects but it was too big"));
}
@@ -10,7 +10,7 @@ import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumDataPacket;
import kamkeel.npcs.network.enums.EnumSyncAction;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
@@ -22,16 +22,13 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* A large sync packet that sends chunked data to the client for a given SyncType
* along with a SyncAction (RELOAD, UPDATE, REMOVE).
*/
public final class SyncPacket extends LargeAbstractPacket {
private EnumSyncType enumSyncType;
private SyncType syncType;
private EnumSyncAction enumSyncAction;
private NBTTagCompound syncData;
private int operationID;
private String operationKey;
private int revision = -1;
private byte[] cachedPayload;
private byte[][] cachedChunks;
@@ -39,23 +36,21 @@ public final class SyncPacket extends LargeAbstractPacket {
public SyncPacket() {
}
/**
* Constructs a new LargeSyncPacket.
*/
public SyncPacket(EnumSyncType enumSyncType, EnumSyncAction enumSyncAction, int catId, NBTTagCompound syncData) {
this(enumSyncType, enumSyncAction, catId, -1, syncData);
public SyncPacket(SyncType syncType, EnumSyncAction enumSyncAction, int catId, NBTTagCompound syncData) {
this(syncType, enumSyncAction, catId, null, -1, syncData);
}
public SyncPacket(EnumSyncType enumSyncType, EnumSyncAction enumSyncAction, int catId, int revision, NBTTagCompound syncData) {
this.enumSyncType = enumSyncType;
public SyncPacket(SyncType syncType, EnumSyncAction enumSyncAction, int operationId, String operationKey, int revision, NBTTagCompound syncData) {
this.syncType = syncType;
this.enumSyncAction = enumSyncAction;
this.syncData = syncData;
this.operationID = catId;
this.operationID = operationId;
this.operationKey = operationKey;
this.revision = revision;
}
public SyncPacket(EnumSyncType enumSyncType, SyncController.CachedSyncPayload payload) {
this.enumSyncType = enumSyncType;
public SyncPacket(SyncType syncType, SyncController.CachedSyncPayload payload) {
this.syncType = syncType;
this.enumSyncAction = EnumSyncAction.RELOAD;
this.operationID = -1;
this.revision = payload.getRevision();
@@ -79,13 +74,21 @@ public final class SyncPacket extends LargeAbstractPacket {
return cachedPayload;
}
boolean hasKey = operationKey != null;
boolean hasNbt = syncData != null;
ByteBuf buffer = Unpooled.buffer();
try {
buffer.writeInt(enumSyncType.ordinal());
buffer.writeInt(syncType.ordinal());
buffer.writeInt(enumSyncAction.ordinal());
buffer.writeInt(operationID);
buffer.writeInt(revision);
ByteBufUtils.writeBigNBT(buffer, syncData);
// UPDATE/REMOVE UNIQUE FIELDS
buffer.writeBoolean(hasKey);
if (hasKey) ByteBufUtils.writeString(buffer, operationKey);
buffer.writeBoolean(hasNbt);
if (hasNbt) ByteBufUtils.writeBigNBT(buffer, syncData);
byte[] bytes = new byte[buffer.readableBytes()];
buffer.readBytes(bytes);
@@ -131,39 +134,40 @@ public final class SyncPacket extends LargeAbstractPacket {
if (CustomNpcs.side() != Side.CLIENT)
return;
// Reconstruct everything from the ByteBuf
int syncTypeOrdinal = data.readInt();
int syncActionOrdinal = data.readInt();
int categoryID = data.readInt();
int incomingRevision = data.readInt();
operationID = data.readInt();
revision = data.readInt();
EnumSyncType type = EnumSyncType.values()[syncTypeOrdinal];
EnumSyncAction action = EnumSyncAction.values()[syncActionOrdinal];
try {
NBTTagCompound tag = ByteBufUtils.readBigNBT(data);
// Now do your client-side logic (similar to your old clientSync() or clientSyncUpdate() approach)
handleSyncPacketClient(type, action, categoryID, incomingRevision, tag);
} catch (RuntimeException e) {
LogWriter.error(String.format("Attempted to Sync %s but it was too big", type.toString()));
// These fields only exist for UPDATE/REMOVE
if (action != EnumSyncAction.RELOAD) {
if (data.readBoolean()) operationKey = ByteBufUtils.readString(data);
if (data.readBoolean()) syncData = ByteBufUtils.readBigNBT(data);
} else
syncData = ByteBufUtils.readBigNBT(data);
syncType = SyncType.byOrdinal(syncTypeOrdinal);
if (syncType == null) {
LogWriter.error("[SyncPacket] Unknown sync type ordinal: " + syncTypeOrdinal + "; skipping");
return;
}
handleSync(syncType, action, operationID, operationKey, revision, syncData);
}
private void handleSyncPacketClient(
EnumSyncType enumSyncType,
EnumSyncAction enumSyncAction,
int id,
int incomingRevision,
NBTTagCompound data
) {
switch (enumSyncAction) {
private void handleSync(SyncType type, EnumSyncAction action, int id, String key, int revision, NBTTagCompound data) {
switch (action) {
case RELOAD:
SyncController.clientSync(enumSyncType, incomingRevision, data);
SyncController.clientHandleAll(type, revision, data);
break;
case UPDATE:
SyncController.clientUpdate(enumSyncType, id, incomingRevision, data);
SyncController.clientHandleUpdate(type, id, key, revision, data);
break;
case REMOVE:
SyncController.clientSyncRemove(enumSyncType, id, incomingRevision);
SyncController.clientHandleRemove(type, id, key, revision);
break;
}
}
@@ -8,13 +8,13 @@ import kamkeel.npcs.network.AbstractPacket;
import kamkeel.npcs.network.PacketChannel;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumPlayerPacket;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import java.io.IOException;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class SyncRevisionInfoPacket extends AbstractPacket {
@@ -23,12 +23,12 @@ public class SyncRevisionInfoPacket extends AbstractPacket {
private String serverKey = "";
private String previousServerKey = "";
private final EnumMap<EnumSyncType, Integer> revisions = new EnumMap<>(EnumSyncType.class);
private final Map<SyncType, Integer> revisions = new LinkedHashMap<>();
public SyncRevisionInfoPacket() {
}
public SyncRevisionInfoPacket(String serverKey, String previousServerKey, EnumMap<EnumSyncType, Integer> revisions) {
public SyncRevisionInfoPacket(String serverKey, String previousServerKey, Map<SyncType, Integer> revisions) {
if (serverKey != null) {
this.serverKey = serverKey;
}
@@ -56,7 +56,7 @@ public class SyncRevisionInfoPacket extends AbstractPacket {
ByteBufUtils.writeString(out, serverKey);
ByteBufUtils.writeString(out, previousServerKey);
out.writeShort(revisions.size());
for (Map.Entry<EnumSyncType, Integer> entry : revisions.entrySet()) {
for (Map.Entry<SyncType, Integer> entry : revisions.entrySet()) {
out.writeInt(entry.getKey().ordinal());
out.writeInt(entry.getValue());
}
@@ -71,13 +71,15 @@ public class SyncRevisionInfoPacket extends AbstractPacket {
String incomingServerKey = ByteBufUtils.readString(in);
String incomingPreviousKey = ByteBufUtils.readString(in);
int revisionCount = in.readUnsignedShort();
EnumMap<EnumSyncType, Integer> incomingRevisions = new EnumMap<>(EnumSyncType.class);
Map<SyncType, Integer> incomingRevisions = new LinkedHashMap<>();
for (int i = 0; i < revisionCount; i++) {
EnumSyncType type = EnumSyncType.values()[in.readInt()];
SyncType type = SyncType.byOrdinal(in.readInt());
int revision = in.readInt();
incomingRevisions.put(type, revision);
if (type != null) {
incomingRevisions.put(type, revision);
}
}
SyncController.handleClientRevisionReport((EntityPlayerMP) player, incomingServerKey, incomingPreviousKey, incomingRevisions);
SyncController.completeLoginRevisionHandshake((EntityPlayerMP) player, incomingServerKey, incomingPreviousKey, incomingRevisions);
}
}
@@ -50,10 +50,7 @@ public final class AbilityHotbarSelectPacket extends AbstractPacket {
// Deselect
data.abilityData.setSelectedIndex(-1);
} else {
int index = data.abilityData.getUnlockedAbilityList().indexOf(key);
if (index >= 0) {
data.abilityData.setSelectedIndex(index);
}
data.abilityData.setSelectedIndex(data.abilityData.getUnlockedAbilityList().indexOf(key));
}
data.save();
}
@@ -13,20 +13,10 @@ import kamkeel.npcs.util.ByteBufUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.LogWriter;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.blocks.tiles.ITilePermission;
import java.io.IOException;
/**
* Convenience packet for saving extra data about Tile Entities. <br>
* <br>
* <b>Any tile entity that uses this packet should implement {@link ITilePermission}</b> <br>
* Not implementing results in the packet treated as malformed and rejected.
*/
public final class TileEntitySavePacket extends AbstractPacket {
public static final String packetName = "Request|TileEntitySave";
@@ -60,40 +50,9 @@ public final class TileEntitySavePacket extends AbstractPacket {
if (!(player instanceof EntityPlayerMP))
return;
NBTTagCompound incomingCompound = ByteBufUtils.readNBT(in);
if (!isCorrectPermission(incomingCompound, player))
return;
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.WAND, EnumItemPacketType.BLOCK))
return;
NoppesUtilServer.saveTileEntity((EntityPlayerMP) player, incomingCompound);
}
private static boolean isCorrectPermission(NBTTagCompound incomingCompound, EntityPlayer player) {
int x = incomingCompound.getInteger("x");
int y = incomingCompound.getInteger("y");
int z = incomingCompound.getInteger("z");
String id = incomingCompound.getString("id");
TileEntity tile = player.worldObj.getTileEntity(x, y, z);
if (tile == null)
return false;
if (!ITilePermission.doesIDMatch(tile.getClass(), id))
return false;
boolean validatesPacket = tile instanceof ITilePermission;
if (!validatesPacket) {
LogWriter.error(String.format("%s tried to use TileEntitySavePacket on %s -- should this class implement ITileValidityChecker??", player.getCommandSenderName(), tile));
return false; // Assume packet is not meant for this entity from the get-go as there is no checking process.
}
ITilePermission validityChecker = (ITilePermission) tile;
CustomNpcsPermissions.Permission perm = validityChecker.getPermission();
return CustomNpcsPermissions.hasPermission(player, perm);
NoppesUtilServer.saveTileEntity((EntityPlayerMP) player, ByteBufUtils.readNBT(in));
}
}
@@ -73,7 +73,7 @@ public final class CategoryItemsRequestPacket extends AbstractPacket {
// Send tag map for the items
HashMap<String, HashSet<UUID>> tagMap = getTagMapByCat(type, categoryId);
if (tagMap != null && !tagMap.isEmpty()) {
if (tagMap != null) {
TagController.sendCategoryTagMap((EntityPlayerMP) player, tagMap);
}
}
@@ -28,6 +28,7 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
private String selected;
private int activeTab;
private String folderName;
private int slot;
private NBTTagCompound compound;
@@ -39,6 +40,15 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
this.isServer = isServer;
this.selected = selected;
this.activeTab = activeTab;
this.folderName = null;
this.slot = slot;
}
public JobSpawnerAddPacket(boolean isServer, String selected, String folderName, int slot) {
this.isServer = isServer;
this.selected = selected;
this.activeTab = -1;
this.folderName = folderName;
this.slot = slot;
}
@@ -75,6 +85,9 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
if (this.isServer) {
ByteBufUtils.writeString(out, selected);
out.writeInt(this.activeTab);
if (this.activeTab == -1) {
ByteBufUtils.writeString(out, folderName != null ? folderName : "");
}
out.writeInt(this.slot);
} else {
out.writeInt(this.slot);
@@ -96,7 +109,15 @@ public final class JobSpawnerAddPacket extends AbstractPacket {
JobSpawner job = (JobSpawner) npc.jobInterface;
boolean useServerClone = in.readBoolean();
if (useServerClone) {
NBTTagCompound compound = ServerCloneController.Instance.getCloneData(null, ByteBufUtils.readString(in), in.readInt());
String selected = ByteBufUtils.readString(in);
int tab = in.readInt();
NBTTagCompound compound;
if (tab == -1) {
String folder = ByteBufUtils.readString(in);
compound = ServerCloneController.Instance.getCloneData(null, selected, folder);
} else {
compound = ServerCloneController.Instance.getCloneData(null, selected, tab);
}
job.setJobCompound(in.readInt(), compound);
} else {
job.setJobCompound(in.readInt(), ByteBufUtils.readNBT(in));
@@ -14,6 +14,7 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.roles.RoleTrader;
import java.io.IOException;
@@ -63,7 +64,13 @@ public final class RoleSavePacket extends AbstractPacket {
if (!PacketUtil.verifyItemPacket(packetName, EnumItemPacketType.WAND, player))
return;
npc.roleInterface.readFromNBT(ByteBufUtils.readNBT(in));
NBTTagCompound roleCompound = ByteBufUtils.readNBT(in);
if (npc.roleInterface instanceof RoleTrader) {
// An admin edit wins over the linked market; the market is written from it afterwards.
((RoleTrader) npc.roleInterface).readFromNBT(roleCompound, false);
} else {
npc.roleInterface.readFromNBT(roleCompound);
}
npc.updateClient = true;
}
}
@@ -6,8 +6,6 @@ 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 net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -38,9 +36,6 @@ public final class TagsGetPacket extends AbstractPacket {
@Override
public void receiveData(ByteBuf in, EntityPlayer player) throws IOException {
if (!PacketUtil.verifyItemPacket(packetName, player, EnumItemPacketType.WAND, EnumItemPacketType.CLONER))
return;
NoppesUtilServer.sendTagDataAll((EntityPlayerMP) player);
}
+26 -1
View File
@@ -26,7 +26,7 @@ public class Register<T> {
protected final String namespace;
protected final Map<String, Supplier<T>> entries = new LinkedHashMap<>();
private Register(String registryKey, String namespace) {
public Register(String registryKey, String namespace) {
this.registryKey = registryKey;
this.namespace = namespace;
}
@@ -36,6 +36,31 @@ public class Register<T> {
return factory.get();
}
public Map<String, Supplier<T>> getEntries() {
return entries;
}
public void forEach(Consumer<T> action) {
entries.values().forEach(s -> action.accept(s.get()));
}
public static <T> Register<T> create(String registryKey, String namespace, String displayName) {
registerNamespace(registryKey, namespace, displayName);
return new Register<>(registryKey, namespace);
}
public static void registerNamespace(String registryKey, String namespace, String displayName) {
if (!REGISTERED_NAMESPACES.containsKey(registryKey))
REGISTERED_NAMESPACES.put(registryKey, new ArrayList<>());
if (REGISTERED_NAMESPACES.get(registryKey).contains(namespace)) {
LogWriter.error("REGISTER: Namespace " + namespace + " already registered for registry " + registryKey + "!");
}
REGISTERED_NAMESPACES.get(registryKey).add(namespace);
NAMESPACE_DISPLAY_NAMES.put(namespace, displayName);
}
public static boolean isEmpty(String registryKey) {
if (REGISTERED_NAMESPACES.isEmpty()) return true;
@@ -786,7 +786,14 @@ public abstract class AbstractDataAbilities {
fireTickEvent(currentAbility, target);
// Script may have completed/cancelled the ability during the tick event
if (currentAbility == null || !currentAbility.isExecuting()) return;
if (currentAbility == null) return;
if (!currentAbility.isExecuting()) {
// tick() can end the ability (DAZED -> IDLE)
if (phaseChanged && currentAbility.getPhase() == AbilityPhase.IDLE) {
handleAbilityCompletion(target);
}
return;
}
// Fire extender tick hook (e.g., per-tick resource drain)
if (!AbilityController.Instance.fireOnAbilityTick(currentAbility, entity, target,
@@ -225,6 +225,9 @@ public class CommonProxy implements IGuiHandler {
public void buildPackageIndex() {
}
public void loadComplete() {
}
public boolean isScriptingEnabled() {
return ConfigScript.ScriptingEnabled;
}
@@ -0,0 +1,35 @@
package noppes.npcs;
import com.gtnewhorizon.gtnhmixins.ILateMixinLoader;
import com.gtnewhorizon.gtnhmixins.LateMixin;
import cpw.mods.fml.relauncher.FMLLaunchHandler;
import noppes.npcs.config.ConfigMixin;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* The mixins into other mods' player models, loaded by UniMixins after every
* mod jar is on the class path. Only found when UniMixins is installed; the
* early plugin then leaves these out.
*/
@LateMixin
public class CustomNPCsLateMixins implements ILateMixinLoader {
@Override
public String getMixinConfig() {
return "mixins.customnpcs.late.json";
}
@Override
public List<String> getMixins(Set<String> loadedMods) {
List<String> mixins = new ArrayList<>();
if (!FMLLaunchHandler.side().isClient() || !ConfigMixin.AnimationMixin) {
return mixins;
}
mixins.addAll(OptionalModelMixins.playerModelMixins(true));
System.out.println("[CustomNPC+] Late player model mixins: " + mixins);
return mixins;
}
}
+5 -1
View File
@@ -125,7 +125,7 @@ import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11.1")
@Mod(modid = "customnpcs", name = "CustomNPC+", version = "1.11.2")
public class CustomNpcs {
@SidedProxy(clientSide = "noppes.npcs.client.ClientProxy", serverSide = "noppes.npcs.CommonProxy")
@@ -318,6 +318,9 @@ public class CustomNpcs {
new AttributeController();
new MagicController();
SyncController.register();
APIRegistry.Instance.register("CNPC+ API", "https://kamkeel.github.io/CustomNPC-Plus/");
}
@@ -340,6 +343,7 @@ public class CustomNpcs {
@EventHandler
public void loadComplete(FMLLoadCompleteEvent ev) {
proxy.loadComplete();
proxy.buildPackageIndex();
// Load built-in animations on the client so they're available for ability preview.
+25 -9
View File
@@ -188,22 +188,33 @@ public class DataAbilities extends AbstractDataAbilities {
if (maxCooldown > minCooldown) {
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
}
cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + ability.getCooldownTicks();
long now = npc.worldObj.getTotalWorldTime();
// Additionally set per-ability cooldown if enabled
if (ability.isPerAbilityCooldown() && ability.getCooldownTicks() > 0) {
long endTime = npc.worldObj.getTotalWorldTime() + ability.getCooldownTicks();
setPerAbilityCooldown(ability.getName(), endTime, ability.getCooldownTicks());
// Global timer only paces the NPC; the ability tracks its own cooldown
cooldownEndTime = now + baseCooldown;
setPerAbilityCooldown(ability.getName(), now + ability.getCooldownTicks(), ability.getCooldownTicks());
} else {
cooldownEndTime = now + baseCooldown + ability.getCooldownTicks();
}
}
@Override
protected void rollChainCooldown(ChainedAbility chain) {
int baseCooldown = minCooldown;
if (maxCooldown > minCooldown) {
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
long now = npc.worldObj.getTotalWorldTime();
boolean perAbility = chain.isPerAbilityCooldown() && chain.getCooldownTicks() > 0;
if (!chain.isIgnoreCooldown()) {
int baseCooldown = minCooldown;
if (maxCooldown > minCooldown) {
baseCooldown = minCooldown + random.nextInt(maxCooldown - minCooldown + 1);
}
cooldownEndTime = perAbility ? now + baseCooldown : now + baseCooldown + chain.getCooldownTicks();
}
if (perAbility) {
setPerAbilityCooldown(chain.getName(), now + chain.getCooldownTicks(), chain.getCooldownTicks());
}
cooldownEndTime = npc.worldObj.getTotalWorldTime() + baseCooldown + chain.getCooldownTicks();
}
@Override
@@ -471,12 +482,17 @@ public class DataAbilities extends AbstractDataAbilities {
return false;
}
// Per-ability cooldown filter: ability may have its own independent cooldown
// Per-ability cooldown filter: ability/chain may have its own independent cooldown
if (!action.isChain()) {
Ability ab = (Ability) action;
if (ab.isPerAbilityCooldown() && isOnPerAbilityCooldown(ab.getName())) {
return false;
}
} else {
ChainedAbility ch = (ChainedAbility) action;
if (ch.isPerAbilityCooldown() && isOnPerAbilityCooldown(ch.getName())) {
return false;
}
}
return true;
@@ -975,6 +975,11 @@ public class EventHooks {
return postAbilityEvent(ability, event);
}
public static boolean onAbilityDefend(Ability ability, AbilityEvent.DefendEvent event) {
if (ability == null || event == null) return false;
return postAbilityEvent(ability, event);
}
public static boolean onAbilityToggle(Ability ability, EntityLivingBase entity, int oldState, int newState) {
if (ability == null || entity == null) return false;
return postAbilityEvent(ability, new AbilityEvent.ToggleEvent(entity, ability, oldState, newState));
@@ -550,14 +550,13 @@ public class NoppesUtilPlayer {
if (data == null)
return false;
if (!data.quest.questInterface.isPartyCompleted(party))
return false;
Quest quest = data.quest;
if (quest == null)
return false;
if (!data.quest.questInterface.isPartyCompleted(party))
return false;
if (data.quest.completion == EnumQuestCompletion.Instant)
EventHooks.onPartyFinished(party, data.quest);
@@ -343,11 +343,6 @@ public class NoppesUtilServer {
sendOpenGui(player, gui, npc, 0, 0, 0);
}
public static void sendOpenGuiNoDelay(EntityPlayer player,
EnumGuiType gui, EntityNPCInterface npc) {
sendOpenGuiNoDelay(player, gui, npc, 0, 0, 0);
}
public static void sendOpenGui(final EntityPlayer player,
final EnumGuiType gui, final EntityNPCInterface npc, final int i, final int j, final int k) {
if (!(player instanceof EntityPlayerMP))
@@ -369,28 +364,6 @@ public class NoppesUtilServer {
ScrollListPacket.sendList((EntityPlayerMP) player, list, EnumScrollData.OPTIONAL);
}
public static void sendOpenGuiNoDelay(final EntityPlayer player,
final EnumGuiType gui, final EntityNPCInterface npc, final int i, final int j, final int k) {
if (!(player instanceof EntityPlayerMP))
return;
setEditingNpc(player, npc);
sendExtraData(player, npc, gui, i, j, k);
if (CustomNpcs.proxy.getServerGuiElement(gui.ordinal(), player, player.worldObj, i, j, k) != null) {
player.openGui(CustomNpcs.instance, gui.ordinal(), player.worldObj, i, j, k);
return;
} else {
GuiOpenPacket.openGUI((EntityPlayerMP) player, gui, i, j, k);
}
ArrayList<String> list = getScrollData(player, gui, npc);
if (list == null || list.isEmpty())
return;
ScrollListPacket.sendList((EntityPlayerMP) player, list, EnumScrollData.OPTIONAL);
}
private static void sendExtraData(EntityPlayer player, EntityNPCInterface npc, EnumGuiType gui, int i, int j, int k) {
if (gui == EnumGuiType.PlayerFollower || gui == EnumGuiType.PlayerFollowerHire || gui == EnumGuiType.PlayerTrader || gui == EnumGuiType.PlayerTransporter) {
sendRoleData(player, npc);
@@ -640,7 +613,7 @@ public class NoppesUtilServer {
playerdata.save();
}
if (pl != null) {
SyncController.syncPlayer((EntityPlayerMP) pl);
SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl);
}
sendPlayerData(type, player, name);
}
@@ -1229,7 +1202,7 @@ public class NoppesUtilServer {
playerdata.save();
if (pl != null) {
SyncController.syncPlayer((EntityPlayerMP) pl);
SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl);
}
}
@@ -1261,7 +1234,7 @@ public class NoppesUtilServer {
playerdata.save();
if (pl != null) {
SyncController.syncPlayer((EntityPlayerMP) pl);
SyncController.dispatchSyncForAllTypes((EntityPlayerMP) pl);
}
}
}
@@ -0,0 +1,115 @@
package noppes.npcs;
import net.minecraft.launchwrapper.Launch;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipFile;
/**
* Which mixins into other mods' player models to load, each only when its
* class is there. With UniMixins the late loader asks after every mod jar is
* on the class path. Without it the early plugin asks before that, finds the
* jar in the mods folder and lends it to the class loader so Mixin can read
* the target.
*/
public final class OptionalModelMixins {
/** Jars lent to the class loader early, taken off the source list again once read. */
private static final List<URL> lentJars = new ArrayList<URL>();
private OptionalModelMixins() {
}
/** UniMixins is a coremod, so its late loader interface is readable this early. */
public static boolean lateLoaderAvailable() {
try {
return Launch.classLoader.getClassBytes("com.gtnewhorizon.gtnhmixins.ILateMixinLoader") != null;
} catch (IOException exception) {
return false;
}
}
/** The mixin names, relative to the late package. */
public static List<String> playerModelMixins(boolean late) {
List<String> mixins = new ArrayList<String>();
if (hasClass("noppes.mpm.client.model.ModelMPM", late)) {
mixins.add("MixinMPMModel");
}
if (hasClass("noppes.mpm.client.model.ModelScaleRenderer", late)) {
mixins.add("MixinMPMModelScaleRenderer");
}
if (hasClass("micdoodle8.mods.galacticraft.core.client.model.ModelPlayerGC", late)) {
mixins.add("MixinGalacticraftPlayerModel");
}
if (hasClass("api.player.model.ModelPlayerAPI", late)) {
mixins.add("MixinPlayerAPIModel");
}
return mixins;
}
/**
* FML lists every class-path source as a mod source, so a lent jar left
* on the list is found twice and refused as a duplicate. Off the list the
* jar stays readable, and FML adds it once itself.
*/
public static void releaseLentJars() {
if (lentJars.isEmpty()) return;
Launch.classLoader.getSources().removeAll(lentJars);
System.out.println("[CustomNPC+] Took " + lentJars.size() + " optional mod jar(s) back off the source list");
lentJars.clear();
}
private static boolean hasClass(String className, boolean late) {
try {
if (Launch.classLoader.getClassBytes(className) != null) {
System.out.println("[CustomNPC+] Optional class " + className + ": on the class path");
return true;
}
} catch (IOException exception) {
System.out.println("[CustomNPC+] Could not inspect optional class " + className + ": " + exception);
}
File jar = late ? null : jarHolding(className);
if (jar == null) {
System.out.println("[CustomNPC+] Optional class " + className + ": not found");
return false;
}
// Mixin drops a @Pseudo target it cannot read when the config is
// prepared. Lending the jar now lets it read the class.
try {
URL url = jar.toURI().toURL();
Launch.classLoader.addURL(url);
lentJars.add(url);
System.out.println("[CustomNPC+] Optional class " + className + ": in mods/"
+ jar.getName() + ", lent to the class path");
return true;
} catch (MalformedURLException exception) {
System.out.println("[CustomNPC+] Optional class " + className + ": in mods/"
+ jar.getName() + " but it could not be lent to the class path: " + exception);
return false;
}
}
/** The jar under mods/ that holds the class, or null. */
private static File jarHolding(String className) {
String entry = className.replace('.', '/') + ".class";
File[] folders = {new File("mods"), new File("mods" + File.separator + "1.7.10")};
for (File folder : folders) {
File[] jars = folder.listFiles();
if (jars == null) continue;
for (File jar : jars) {
if (!jar.getName().toLowerCase().endsWith(".jar")) continue;
try (ZipFile zip = new ZipFile(jar)) {
if (zip.getEntry(entry) != null) return jar;
} catch (IOException ignored) {
// Not a readable jar; nothing to find in it.
}
}
}
return null;
}
}
@@ -9,7 +9,9 @@ import kamkeel.npcs.addon.DBCAddon;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.AttributeController;
import kamkeel.npcs.controllers.data.attribute.tracker.PlayerAttributeTracker;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper;
import kamkeel.npcs.controllers.sync.handlers.PlayerDataSyncHandler;
import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.type.AbilityCounter;
import kamkeel.npcs.controllers.data.ability.type.AbilityDefend;
@@ -141,7 +143,7 @@ public class ScriptPlayerEventHandler {
}
if (playerData.updateClient) {
SyncController.syncPlayerData((EntityPlayerMP) player, true);
PlayerDataSyncHandler.syncPlayerData((EntityPlayerMP) player, true);
playerData.updateClient = false;
}
@@ -151,8 +153,8 @@ public class ScriptPlayerEventHandler {
if (player.ticksExisted % 10 == 0) {
EntityPlayerMP mp = (EntityPlayerMP) player;
SyncController.syncEffects(mp);
SyncController.syncAbilityCooldowns(mp);
PlayerEffectSyncHelper.syncEffects(mp);
PlayerAbilitySyncHelper.syncAbilityCooldowns(mp);
PlayerAbilitySyncPacket.sendToPlayer(mp);
playerData.abilityData.ensureLockStateClear();
}
@@ -4,13 +4,15 @@ import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.sync.handlers.CarpentryRecipeSyncHandler;
import kamkeel.npcs.controllers.sync.handlers.WorkbenchRecipeSyncHandler;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargeTracker;
import kamkeel.npcs.entity.EntityEnergyBarrier;
import kamkeel.npcs.entity.EntityEnergyDome;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSoundOperation;
import kamkeel.npcs.network.enums.EnumSyncAction;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.data.ClonerPacket;
import kamkeel.npcs.network.packets.data.MarkDataPacket;
import kamkeel.npcs.network.packets.data.SoundManagementPacket;
@@ -136,7 +138,7 @@ public class ServerEventsHandler {
mounted = event.target;
if (isRemote)
CustomNpcs.proxy.openGui(MathHelper.floor_double(mounted.posX), MathHelper.floor_double(mounted.posY), MathHelper.floor_double(mounted.posZ), EnumGuiType.MobSpawnerMounter, event.entityPlayer);
} else if (item.getItem() == CustomItems.wand && !isRemote && event.target instanceof EntityVillager) {
} else if (item.getItem() == CustomItems.wand && event.target instanceof EntityVillager) {
if (!CustomNpcsPermissions.hasPermission(event.entityPlayer, CustomNpcsPermissions.EDIT_VILLAGER))
return;
event.setCanceled(true);
@@ -255,20 +257,22 @@ public class ServerEventsHandler {
if (block == Blocks.crafting_table && event.action == Action.RIGHT_CLICK_BLOCK && !player.worldObj.isRemote) {
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.WORKBENCH_RECIPES,
SyncType.WORKBENCH_RECIPES,
EnumSyncAction.RELOAD,
-1,
SyncController.getCurrentRevision(EnumSyncType.WORKBENCH_RECIPES),
SyncController.workbenchNBT()
null,
SyncController.getCurrentServerRevision(SyncType.WORKBENCH_RECIPES),
WorkbenchRecipeSyncHandler.getInstance().serializeAll()
), (EntityPlayerMP) player);
}
if (block == CustomItems.carpentyBench && event.action == Action.RIGHT_CLICK_BLOCK && !player.worldObj.isRemote) {
PacketHandler.Instance.sendToPlayer(new SyncPacket(
EnumSyncType.CARPENTRY_RECIPES,
SyncType.CARPENTRY_RECIPES,
EnumSyncAction.RELOAD,
-1,
SyncController.getCurrentRevision(EnumSyncType.CARPENTRY_RECIPES),
SyncController.carpentryNBT()
null,
SyncController.getCurrentServerRevision(SyncType.CARPENTRY_RECIPES),
CarpentryRecipeSyncHandler.getInstance().serializeAll()
), (EntityPlayerMP) player);
}
if ((block == CustomItems.banner || block == CustomItems.wallBanner || block == CustomItems.sign) && event.action == Action.RIGHT_CLICK_BLOCK) {
@@ -6,6 +6,8 @@ import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import kamkeel.npcs.controllers.ProfileController;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.controllers.sync.handlers.PlayerAbilitySyncHelper;
import kamkeel.npcs.controllers.sync.handlers.PlayerEffectSyncHelper;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.WorldServer;
import noppes.npcs.controllers.AuctionController;
@@ -45,13 +47,12 @@ public class ServerTickHandler {
playerData.onLogin();
}
ProfileController.Instance.login(player);
SyncController.beginLogin(player);
SyncController.syncEffects(player);
PlayerEffectSyncHelper.syncEffects(player);
ScriptController.Instance.syncClientScripts(player);
// Sync clean ability state to the new client (after beginLogin initializes sync state)
SyncController.syncAbilities(player);
PlayerAbilitySyncHelper.syncAbilities(player);
// Send auction notifications on login
if (AuctionController.Instance != null) {
@@ -4,6 +4,7 @@ import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagInt;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.constants.EnumPotionType;
import noppes.npcs.controllers.data.Line;
import noppes.npcs.controllers.data.Lines;
import noppes.npcs.entity.EntityNPCInterface;
@@ -23,6 +24,13 @@ public class VersionCompatibility {
boolean aimShot = compound.getBoolean("AimWhileShooting");
compound.setInteger("AimType", !aimShot ? 0 : 1);
}
// Restore burning on Fire projectiles saved before pBurnItem existed
if (compound.hasKey("pEffect") && !compound.hasKey("pBurnItem")) {
if (EnumPotionType.fromOrdinal(compound.getInteger("pEffect")) == EnumPotionType.Fire) {
compound.setBoolean("pBurnItem", true);
}
}
}
if (npc.npcVersion < 22) {
if (compound.hasKey("CanLeap")) {
@@ -10,7 +10,7 @@ public class EntityAITransform extends EntityAIBase {
public EntityAITransform(EntityNPCInterface npc) {
this.npc = npc;
setMutexBits(AiMutex.PASSIVE);
setMutexBits(0);
}
@Override
@@ -67,10 +67,6 @@ public class BlockBorder extends BlockContainer {
}
tile.rotation = l;
if (par5EntityLivingBase instanceof EntityPlayer && par1World.isRemote) {
CustomNpcs.proxy.openGui(x, y, z, EnumGuiType.Border, (EntityPlayer) par5EntityLivingBase);
}
}
private TileBorder getTile(World world, int x, int y, int z) {
@@ -40,7 +40,6 @@ public class BlockCampfire extends BlockLightable {
ItemStack item = player.inventory.getCurrentItem();
if (item == null)
return true;
int meta = world.getBlockMetadata(x, y, z);
if ((item.getItem() == Items.flint || item.getItem() == Items.flint_and_steel) && unlitBlock() == this) {
super.onBlockActivated(world, x, y, z, player, par6, par7, par8, par9);
@@ -49,13 +49,6 @@ public class BlockNpcRedstone extends BlockContainer {
par1World.notifyBlocksOfNeighborChange(par2, par3, par4 + 1, this);
}
@Override
public void onBlockPlacedBy(World world, int i, int j, int k, EntityLivingBase entityliving, ItemStack item) {
if (entityliving instanceof EntityPlayer && world.isRemote) {
CustomNpcs.proxy.openGui(i, j, k, EnumGuiType.RedstoneBlock, (EntityPlayer) entityliving);
}
}
@Override
public void onBlockDestroyedByPlayer(World par1World, int par2, int par3, int par4, int par5) {
onBlockAdded(par1World, par2, par3, par4);
@@ -1,17 +0,0 @@
package noppes.npcs.blocks.tiles;
import net.minecraft.tileentity.TileEntity;
import noppes.npcs.CustomNpcsPermissions;
public interface ITilePermission {
CustomNpcsPermissions.Permission getPermission();
static boolean doesIDMatch(Class<? extends TileEntity> tileClass, String givenID) {
if (givenID == null)
return false;
Object entry = TileEntity.classToNameMap.get(tileClass);
return givenID.equals(entry);
}
}
@@ -12,12 +12,11 @@ import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatComponentTranslation;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.controllers.data.Availability;
import java.util.List;
public class TileBorder extends TileEntity implements IEntitySelector, ITilePermission {
public class TileBorder extends TileEntity implements IEntitySelector {
public Availability availability = new Availability();
public AxisAlignedBB boundingbox;
public int rotation = 0;
@@ -110,9 +109,4 @@ public class TileBorder extends TileEntity implements IEntitySelector, ITilePerm
public boolean isEntityApplicable(Entity var1) {
return var1 instanceof EntityPlayerMP || var1 instanceof EntityEnderPearl;
}
@Override
public CustomNpcsPermissions.Permission getPermission() {
return CustomNpcsPermissions.EDIT_BLOCKS;
}
}
@@ -6,13 +6,12 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import noppes.npcs.CustomNpcs;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.blocks.BlockNpcRedstone;
import noppes.npcs.controllers.data.Availability;
import java.util.List;
public class TileRedstoneBlock extends TileEntity implements ITilePermission {
public class TileRedstoneBlock extends TileEntity {
public int onRange = 6;
public int offRange = 10;
@@ -139,9 +138,4 @@ public class TileRedstoneBlock extends TileEntity implements ITilePermission {
public boolean canUpdate() {
return true;
}
@Override
public CustomNpcsPermissions.Permission getPermission() {
return CustomNpcsPermissions.EDIT_REDSTONE;
}
}
@@ -6,7 +6,6 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.StatCollector;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.constants.EnumQuestType;
import noppes.npcs.controllers.PartyController;
import noppes.npcs.controllers.data.Party;
@@ -19,7 +18,7 @@ import noppes.npcs.quests.QuestLocation;
import java.util.ArrayList;
import java.util.List;
public class TileWaypoint extends TileEntity implements ITilePermission {
public class TileWaypoint extends TileEntity {
public String name = "";
@@ -103,9 +102,4 @@ public class TileWaypoint extends TileEntity implements ITilePermission {
compound.setString("LocationName", name);
compound.setInteger("LocationRange", range);
}
@Override
public CustomNpcsPermissions.Permission getPermission() {
return CustomNpcsPermissions.EDIT_WAYPOINT;
}
}
@@ -1,6 +1,6 @@
package noppes.npcs.client;
import kamkeel.npcs.network.enums.EnumSyncType;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.controllers.MusicController;
@@ -18,8 +18,8 @@ import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.SkinOverlay;
import noppes.npcs.util.CacheHashMap;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
@@ -32,14 +32,14 @@ public class ClientCacheHandler {
private static String activeServerKey = "";
private static String lastServerKey = "";
private static final Map<String, EnumMap<EnumSyncType, Integer>> clientRevisionCache = new HashMap<>();
private static final Map<String, Map<SyncType, Integer>> clientRevisionCache = new HashMap<>();
public static Party party;
public static boolean allowProfiles = true;
public static boolean allowParties = true;
public static void setActiveServer(String serverKey, EnumMap<EnumSyncType, Integer> serverRevisions) {
public static void setActiveServer(String serverKey, Map<SyncType, Integer> serverRevisions) {
String normalizedKey = serverKey == null ? "" : serverKey;
String previousKey = activeServerKey == null ? "" : activeServerKey;
lastServerKey = previousKey;
@@ -54,9 +54,9 @@ public class ClientCacheHandler {
return;
}
EnumMap<EnumSyncType, Integer> cached = clientRevisionCache.computeIfAbsent(
Map<SyncType, Integer> cached = clientRevisionCache.computeIfAbsent(
activeServerKey,
ignored -> new EnumMap<>(EnumSyncType.class)
ignored -> new LinkedHashMap<>()
);
if (serverRevisions != null && !serverRevisions.isEmpty()) {
cached.keySet().retainAll(serverRevisions.keySet());
@@ -67,19 +67,19 @@ public class ClientCacheHandler {
return lastServerKey == null ? "" : lastServerKey;
}
public static EnumMap<EnumSyncType, Integer> getCachedRevisionsForServer(String serverKey) {
public static Map<SyncType, Integer> getCachedRevisionsForServer(String serverKey) {
String key = serverKey == null ? "" : serverKey;
if (key.isEmpty()) {
return new EnumMap<>(EnumSyncType.class);
return new LinkedHashMap<>();
}
EnumMap<EnumSyncType, Integer> revisions = clientRevisionCache.get(key);
Map<SyncType, Integer> revisions = clientRevisionCache.get(key);
if (revisions == null) {
return new EnumMap<>(EnumSyncType.class);
return new LinkedHashMap<>();
}
return new EnumMap<>(revisions);
return new LinkedHashMap<>(revisions);
}
public static void updateClientRevision(EnumSyncType type, int revision) {
public static void updateClientRevision(SyncType type, int revision) {
if (revision < 0) {
return;
}
@@ -87,9 +87,9 @@ public class ClientCacheHandler {
if (key.isEmpty()) {
return;
}
EnumMap<EnumSyncType, Integer> revisions = clientRevisionCache.computeIfAbsent(
Map<SyncType, Integer> revisions = clientRevisionCache.computeIfAbsent(
key,
ignored -> new EnumMap<>(EnumSyncType.class)
ignored -> new LinkedHashMap<>()
);
revisions.put(type, revision);
}
@@ -126,14 +126,11 @@ public class ClientCacheHandler {
ClientCacheHandler.playerAnimations.clear();
ProfileClientConfig.reset();
// Clear Texture Caches
GuiSoundSelection.cachedDomains.clear();
GuiTextureSelection.cachedTextures.clear();
// Clear music/bard sounds
MusicController.Instance.stopAllSounds();
// Clear Quest Tracker
HudComponent component = ClientHudManager.getInstance().getHudComponents().get(EnumHudComponent.QuestTracker);
if (component != null) {
component.loadData(new NBTTagCompound());
@@ -146,7 +143,6 @@ public class ClientCacheHandler {
ClientCacheHandler.customOverlays.clear();
ClientCacheHandler.skinOverlays.clear();
// Clear Texture Caches
GuiSoundSelection.cachedDomains.clear();
GuiTextureSelection.cachedTextures.clear();
}
@@ -28,6 +28,7 @@ import noppes.npcs.client.gui.hud.QuestTrackingComponent;
import noppes.npcs.client.gui.hud.ability.AbilityHotbarComponent;
import noppes.npcs.client.gui.player.AuctionTooltipHandler;
import noppes.npcs.client.KeyPressHandler;
import noppes.npcs.client.model.PlayerModelAnimation;
import noppes.npcs.client.renderer.MarkRenderer;
import noppes.npcs.client.renderer.RenderCNPCPlayer;
import noppes.npcs.constants.EnumAnimationPart;
@@ -46,6 +47,7 @@ import java.util.Map;
import java.util.Set;
public class ClientEventHandler {
private static boolean loggedPlayerRenderer;
public static final RenderCNPCPlayer renderCNPCSelf = new RenderCNPCPlayer();
public static final RenderCNPCPlayer renderCNPCPlayer = new RenderCNPCPlayer();
public static HashMap<Integer, Long> disabledButtonTimes = new HashMap<>();
@@ -62,6 +64,7 @@ public class ClientEventHandler {
public static boolean renderingEntityInGUI;
public static EntityNPCInterface renderingNpc;
public static EntityPlayer renderingPlayer;
public static boolean renderingPlayerAnimation;
public static HashMap<EnumAnimationPart, String[]> partNames = new HashMap<>();
public static HashMap<Class<?>, Field[]> declaredFieldCache = new HashMap<>();
@@ -70,6 +73,7 @@ public class ClientEventHandler {
public static ModelBase playerModel;
private Class<?> renderPlayerJBRA;
private PlayerModelAnimation.Pose equippedItemPose;
public ClientEventHandler() {
try {
@@ -161,6 +165,7 @@ public class ClientEventHandler {
public void onRenderEntity(RenderLivingEvent.Pre event) {
if (event.entity instanceof EntityNPCInterface) {
ClientEventHandler.renderingPlayer = null;
ClientEventHandler.renderingPlayerAnimation = false;
ClientEventHandler.renderingNpc = (EntityNPCInterface) event.entity;
}
ClientEventHandler.renderer = event.renderer;
@@ -227,6 +232,17 @@ public class ClientEventHandler {
public void onRenderPlayer(RenderPlayerEvent.Pre event) {
ClientEventHandler.renderingNpc = null;
ClientEventHandler.renderingPlayer = event.entityPlayer;
ClientEventHandler.renderingPlayerAnimation = PlayerModelAnimation.shouldApply(event.entityPlayer);
if (!loggedPlayerRenderer) {
loggedPlayerRenderer = true;
String model = event.renderer.mainModel == null ? "null"
: event.renderer.mainModel.getClass().getName();
String arm = event.renderer.modelBipedMain == null
|| event.renderer.modelBipedMain.bipedRightArm == null ? "null"
: event.renderer.modelBipedMain.bipedRightArm.getClass().getName();
System.out.println("[CustomNPC+] Active player renderer="
+ event.renderer.getClass().getName() + "; model=" + model + "; arm=" + arm);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
@@ -237,8 +253,10 @@ public class ClientEventHandler {
@SubscribeEvent
public void onRenderPlayer(RenderPlayerEvent.Post event) {
restoreEquippedItemPose();
EntityPlayer player = event.entityPlayer;
ClientEventHandler.renderingPlayer = null;
ClientEventHandler.renderingPlayerAnimation = false;
if (hasOverlays(player)) {
if (renderPlayerJBRA != null && renderPlayerJBRA.isInstance(event.renderer))
@@ -266,6 +284,35 @@ public class ClientEventHandler {
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void applyEquippedItemPose(RenderPlayerEvent.Specials.Pre event) {
restoreEquippedItemPose();
if (!ClientEventHandler.renderingPlayerAnimation) {
return;
}
ModelBiped model = event.renderer.modelBipedMain;
if (model == null) {
return;
}
equippedItemPose = PlayerModelAnimation.capture(model);
PlayerModelAnimation.apply(model);
}
@SubscribeEvent(priority = EventPriority.LOWEST, receiveCanceled = true)
public void restoreEquippedItemPose(RenderPlayerEvent.Specials.Post event) {
restoreEquippedItemPose();
}
private void restoreEquippedItemPose() {
if (equippedItemPose == null) {
return;
}
equippedItemPose.restore();
equippedItemPose = null;
}
@SubscribeEvent
public void cancelSpecials(RenderPlayerEvent.Specials.Pre event) {
if (event.renderer instanceof RenderCNPCPlayer) {
@@ -344,7 +344,6 @@ public class ClientProxy extends CommonProxy {
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(CustomItems.shortLamp), new ItemShortLampRenderer());
MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(CustomItems.tallLamp), new ItemTallLampRenderer());
}
Minecraft mc = Minecraft.getMinecraft();
NPCButton = new KeyBinding("NPC Inventory", Keyboard.KEY_N, "key.categories.customnpc");
SpecialKey = new KeyBinding("key.customnpcs.special", Keyboard.KEY_GRAVE, "key.categories.customnpc");
@@ -384,14 +383,6 @@ public class ClientProxy extends CommonProxy {
// Lightning effect rendering system
MinecraftForge.EVENT_BUS.register(new LightningHandler());
if (ConfigClient.InventoryGuiEnabled) {
MinecraftForge.EVENT_BUS.register(new TabRegistry());
if (TabRegistry.getTabList().isEmpty()) {
TabRegistry.registerTab(new InventoryTabVanilla());
}
TabRegistry.registerTab(new InventoryTabCustomNpc());
}
}
public FakePlayer getCommandPlayer(IWorld world) {
@@ -720,9 +711,7 @@ public class ClientProxy extends CommonProxy {
if (!player.worldObj.isRemote || !(guiscreen instanceof GuiScreen))
return;
if (guiscreen != null) {
minecraft.displayGuiScreen((GuiScreen) guiscreen);
}
minecraft.displayGuiScreen((GuiScreen) guiscreen);
}
@@ -817,8 +806,7 @@ public class ClientProxy extends CommonProxy {
if (location == null)
return;
TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager();
if (location != null)
texturemanager.bindTexture((ResourceLocation) location);
texturemanager.bindTexture((ResourceLocation) location);
} catch (NullPointerException ex) {
} catch (ReportedException ex) {
@@ -862,6 +850,18 @@ public class ClientProxy extends CommonProxy {
return Minecraft.getMinecraft().currentScreen != null;
}
@Override
public void loadComplete() {
// Deferred from load() so TConstruct registers its tabs first
if (ConfigClient.InventoryGuiEnabled) {
MinecraftForge.EVENT_BUS.register(new TabRegistry());
if (TabRegistry.getTabList().isEmpty()) {
TabRegistry.registerTab(new InventoryTabVanilla());
}
TabRegistry.registerTab(new InventoryTabCustomNpc());
}
}
public void buildPackageIndex() {
try {
PackageFinder.init(Thread.currentThread().getContextClassLoader());
@@ -38,6 +38,7 @@ import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.Vector;
public class NoppesUtil {
@@ -51,11 +52,15 @@ public class NoppesUtil {
}
public static void updateSkinOverlayData(EntityPlayer player, NBTTagCompound compound) {
updateSkinOverlayData(player.getUniqueID(), compound);
}
public static void updateSkinOverlayData(UUID playerUUID, NBTTagCompound compound) {
HashMap<Integer, SkinOverlay> skinOverlays = new HashMap<>();
HashMap<Integer, SkinOverlay> oldOverlays = new HashMap<>();
NBTTagList skinOverlayList = compound.getTagList("SkinOverlayData", 10);
if (ClientCacheHandler.skinOverlays.containsKey(player.getUniqueID())) {
oldOverlays = ClientCacheHandler.skinOverlays.get(player.getUniqueID());
if (ClientCacheHandler.skinOverlays.containsKey(playerUUID)) {
oldOverlays = ClientCacheHandler.skinOverlays.get(playerUUID);
}
for (int i = 0; i < skinOverlayList.tagCount(); i++) {
@@ -66,7 +71,7 @@ public class NoppesUtil {
}
skinOverlays.put(tagID, overlay);
}
ClientCacheHandler.skinOverlays.put(player.getUniqueID(), skinOverlays);
ClientCacheHandler.skinOverlays.put(playerUUID, skinOverlays);
}
public static void clickSound() {
@@ -127,7 +127,6 @@ public class GuiNpcMobSpawnerMounter extends GuiNPCInterface implements IGuiData
return;
}
ArrayList<String> list = new ArrayList<String>();
this.list = ClientCloneController.Instance.getClones(activeTab);
scroll.setList(getSearchList());
}
@@ -8,22 +8,26 @@ import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.client.controllers.ClientCloneController;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiMenuSideButton;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcTextField;
import noppes.npcs.client.gui.util.ICustomScrollListener;
import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.data.CloneFolder;
import java.util.ArrayList;
import java.util.List;
public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData {
public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiData, ICustomScrollListener {
private GuiCustomScroll scroll;
private GuiCustomScroll navScroll;
private List<String> list;
private List<String> navList = new ArrayList<String>();
private static String search = "";
public int activeTab = 1;
public String activeFolder = null;
public boolean isServer = false;
public GuiNpcMobSpawnerSelector() {
@@ -50,40 +54,62 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
addButton(new GuiNpcButton(0, guiLeft + 171, guiTop + 80, 80, 20, "gui.done"));
addButton(new GuiNpcButton(1, guiLeft + 171, guiTop + 103, 80, 20, "gui.cancel"));
addSideButton(new GuiMenuSideButton(21, guiLeft - 90, this.guiTop + 2, 90, 22, "1"));
addSideButton(new GuiMenuSideButton(22, guiLeft - 90, this.guiTop + 23, 90, 22, "2"));
addSideButton(new GuiMenuSideButton(23, guiLeft - 90, this.guiTop + 44, 90, 22, "3"));
addSideButton(new GuiMenuSideButton(24, guiLeft - 90, this.guiTop + 65, 90, 22, "4"));
addSideButton(new GuiMenuSideButton(25, guiLeft - 90, this.guiTop + 86, 90, 22, "5"));
addSideButton(new GuiMenuSideButton(26, guiLeft - 45, this.guiTop + 107, 45, 22, "6"));
addSideButton(new GuiMenuSideButton(27, guiLeft - 90, this.guiTop + 107, 45, 22, "7"));
addSideButton(new GuiMenuSideButton(28, guiLeft - 45, this.guiTop + 128, 45, 22, "8"));
addSideButton(new GuiMenuSideButton(29, guiLeft - 90, this.guiTop + 128, 45, 22, "9"));
addSideButton(new GuiMenuSideButton(30, guiLeft - 45, this.guiTop + 149, 45, 22, "10"));
addSideButton(new GuiMenuSideButton(31, guiLeft - 90, this.guiTop + 149, 45, 22, "11"));
addSideButton(new GuiMenuSideButton(32, guiLeft - 45, this.guiTop + 170, 45, 22, "12"));
addSideButton(new GuiMenuSideButton(33, guiLeft - 90, this.guiTop + 170, 45, 22, "13"));
addSideButton(new GuiMenuSideButton(34, guiLeft - 45, this.guiTop + 191, 45, 22, "14"));
addSideButton(new GuiMenuSideButton(35, guiLeft - 90, this.guiTop + 191, 45, 22, "15"));
// Navigation scroll (tabs + folders) replacing hardcoded side buttons
buildNavList();
if (navScroll == null) {
navScroll = new GuiCustomScroll(this, 1);
} else {
navScroll.clear();
}
navScroll.setSize(90, 210);
navScroll.guiLeft = guiLeft - 94;
navScroll.guiTop = guiTop + 2;
navScroll.setList(navList);
navScroll.setSelected(getNavSelection());
addScroll(navScroll);
getSideButton(20 + activeTab).active = true;
showClones();
}
private void buildNavList() {
navList.clear();
for (int i = 1; i <= 15; i++) {
navList.add("Tab " + i);
}
if (ClientCloneController.Instance != null) {
for (CloneFolder folder : ClientCloneController.Instance.getFolderList()) {
navList.add(folder.name);
}
}
}
private String getNavSelection() {
if (activeFolder != null) return activeFolder;
if (activeTab >= 1 && activeTab <= 15) return "Tab " + activeTab;
return "Tab 1";
}
public String getSelected() {
return scroll.getSelected();
}
private void showClones() {
if (isServer) {
PacketClient.sendClient(new CloneListPacket(activeTab));
if (activeFolder != null) {
PacketClient.sendClient(new CloneListPacket(activeFolder));
} else {
PacketClient.sendClient(new CloneListPacket(activeTab));
}
return;
}
ArrayList<String> list = new ArrayList<String>();
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeTab));
if (activeFolder != null && ClientCloneController.Instance != null) {
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeFolder));
} else if (ClientCloneController.Instance != null) {
this.list = new ArrayList<String>(ClientCloneController.Instance.getClones(activeTab));
} else {
this.list = new ArrayList<String>();
}
scroll.setList(getSearchList());
}
@@ -97,6 +123,7 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
}
private List<String> getSearchList() {
if (list == null) list = new ArrayList<String>();
if (search.isEmpty())
return new ArrayList<String>(list);
List<String> list = new ArrayList<String>();
@@ -112,8 +139,15 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
if (sel == null)
return null;
NBTTagCompound compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab);
compound.setString("ClonedName", sel);
NBTTagCompound compound;
if (activeFolder != null && ClientCloneController.Instance != null) {
compound = ClientCloneController.Instance.getCloneData(player, sel, activeFolder);
} else {
compound = ClientCloneController.Instance.getCloneData(player, sel, activeTab);
}
if (compound != null) {
compound.setString("ClonedName", sel);
}
return compound;
}
@@ -126,9 +160,28 @@ public class GuiNpcMobSpawnerSelector extends SubGuiInterface implements IGuiDat
scroll.clear();
close();
}
if (id > 20) {
activeTab = id - 20;
initGui();
}
@Override
public void customScrollClicked(int i, int j, int k, GuiCustomScroll guiCustomScroll) {
if (guiCustomScroll.id == 1) {
String selected = navScroll.getSelected();
if (selected == null) return;
if (selected.startsWith("Tab ")) {
try {
int tabNum = Integer.parseInt(selected.substring(4));
if (tabNum >= 1 && tabNum <= 15) {
activeTab = tabNum;
activeFolder = null;
}
} catch (NumberFormatException ignored) {
}
} else {
activeFolder = selected;
activeTab = -1;
}
showClones();
}
}
@@ -112,19 +112,19 @@ public class SubGuiNpcAvailabilityDialog extends SubGuiInterface implements GuiS
}
if (button.id == 10) {
slot = 1;
setSubGui(new GuiDialogSelection(availabitily.questId));
setSubGui(new GuiDialogSelection(availabitily.dialogId));
}
if (button.id == 11) {
slot = 2;
setSubGui(new GuiDialogSelection(availabitily.quest2Id));
setSubGui(new GuiDialogSelection(availabitily.dialog2Id));
}
if (button.id == 12) {
slot = 3;
setSubGui(new GuiDialogSelection(availabitily.quest3Id));
setSubGui(new GuiDialogSelection(availabitily.dialog3Id));
}
if (button.id == 13) {
slot = 4;
setSubGui(new GuiDialogSelection(availabitily.quest4Id));
setSubGui(new GuiDialogSelection(availabitily.dialog4Id));
}
if (button.id == 20) {
availabitily.dialogId = -1;
@@ -81,7 +81,6 @@ public class SubGuiNpcBiomes extends SubGuiInterface {
if (scroll1.hasSelected()) {
data.biomes.add(scroll1.getSelected());
scroll1.selected = -1;
scroll1.selected = -1;
initGui();
}
}
@@ -4,6 +4,7 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.SubGuiInterface;
@@ -12,6 +13,17 @@ public class SubGuiTrapPresetSelector extends SubGuiInterface {
public String selectedPreset = null;
public static FieldDef createPresetField(java.util.function.Consumer<String> applyPreset) {
return FieldDef.subGuiField("gui.applyPreset",
SubGuiTrapPresetSelector::new,
gui -> {
SubGuiTrapPresetSelector selector = (SubGuiTrapPresetSelector) gui;
if (selector.selectedPreset != null) {
applyPreset.accept(selector.selectedPreset);
}
});
}
private static final String[] PRESET_NAMES = {"HIDDEN", "VENOM", "EXPLOSIVE", "CURSED", "SHOCK", "SNARE"};
private static final String[] PRESET_LABELS = {
"ability.preset.hidden", "ability.preset.venom", "ability.preset.explosive",
@@ -4,6 +4,7 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.SubGuiInterface;
@@ -12,6 +13,17 @@ public class SubGuiZonePresetSelector extends SubGuiInterface {
public String selectedPreset = null;
public static FieldDef createPresetField(java.util.function.Consumer<String> applyPreset) {
return FieldDef.subGuiField("gui.applyPreset",
SubGuiZonePresetSelector::new,
gui -> {
SubGuiZonePresetSelector selector = (SubGuiZonePresetSelector) gui;
if (selector.selectedPreset != null) {
applyPreset.accept(selector.selectedPreset);
}
});
}
private static final String[] PRESET_NAMES = {"DEFAULT", "TOXIC", "INFERNO", "ARCANE", "ELECTRIC", "FROST"};
private static final String[] PRESET_LABELS = {
"ability.preset.default", "ability.preset.toxic", "ability.preset.inferno",
@@ -1,6 +1,8 @@
package noppes.npcs.client.gui.advanced;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.util.StatCollector;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcLabel;
@@ -11,6 +13,7 @@ import noppes.npcs.client.gui.util.SubGuiInterface;
import noppes.npcs.controllers.MagicController;
import noppes.npcs.controllers.data.Magic;
import noppes.npcs.controllers.data.MagicData;
import noppes.npcs.controllers.data.MagicEntry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -36,6 +39,22 @@ public class SubGuiAbilityMagic extends SubGuiInterface implements ICustomScroll
private GuiNpcTextField splitField;
public static FieldDef createMagicField(MagicData magicData) {
return FieldDef.subGuiField("ability.magic.editor",
() -> new SubGuiAbilityMagic(magicData.copy()),
gui -> {
MagicData result = ((SubGuiAbilityMagic) gui).magicData;
magicData.getMagics().clear();
for (Map.Entry<Integer, MagicEntry> e : result.getMagics().entrySet()) {
magicData.getMagics().put(e.getKey(), e.getValue());
}
})
.buttonLabel(() -> magicData.isEmpty()
? StatCollector.translateToLocal("ability.magic.usesCaster")
: magicData.getMagics().size() + " Magic(s)")
.tab("General");
}
public SubGuiAbilityMagic(MagicData data) {
this.magicData = data;
setBackground("menubg.png");
@@ -33,6 +33,7 @@ import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BooleanSupplier;
import static kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition.MAX_CONDITIONS;
@@ -153,7 +154,11 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
fieldDefs.add(FieldDef.boolField("gui.enabled", chain::isEnabled, chain::setEnabled).tab("General"));
fieldDefs.add(FieldDef.intField("ability.weight", chain::getWeight, chain::setWeight).range(1, 100).tab("General"));
fieldDefs.add(FieldDef.boolField("ability.windUpAll", chain::isWindUpAll, chain::setWindUpAll).tab("General"));
fieldDefs.add(FieldDef.intField("ability.cooldown", chain::getCooldownTicks, chain::setCooldownTicks).range(0, 12000).tab("General"));
fieldDefs.add(FieldDef.row(
FieldDef.intField("ability.cooldown", chain::getCooldownTicks, chain::setCooldownTicks).range(0, 12000),
FieldDef.boolField("ability.perAbilityCooldown", chain::isPerAbilityCooldown, chain::setPerAbilityCooldown)
).tab("General"));
fieldDefs.add(FieldDef.boolField("ability.ignoreCooldown", chain::isIgnoreCooldown, chain::setIgnoreCooldown).tab("General"));
// ── Target tab ───────────────────────────────────────────────
fieldDefs.add(FieldDef.row(
@@ -163,16 +168,20 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
// ── Icon tab ──────────────────────────────────────────────
AbilityIconData chainIcon = AbilityIconData.fromChainedAbility(chain);
BooleanSupplier isCustomIcon = chainIcon::isEnabled;
fieldDefs.add(FieldDef.section("ability.section.icon").tab("Icon"));
fieldDefs.add(FieldDef.boolField("ability.hasIcon", chainIcon::isEnabled, chainIcon::setEnabled).tab("Icon"));
fieldDefs.add(FieldDef.row(
FieldDef.intField("gui.width", chainIcon::getWidth, chainIcon::setWidth).range(1, 256),
FieldDef.intField("gui.height", chainIcon::getHeight, chainIcon::setHeight).range(1, 256)
).tab("Icon"));
fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f));
).tab("Icon").visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.floatField("gui.scale", chainIcon::getScale, chainIcon::setScale).tab("Icon").range(0.1f, 10.0f).visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.intField("ability.icon.layers", chainIcon::getLayerCount, chainIcon::setLayerCount)
.tab("Icon").range(1, AbilityIconData.MAX_LAYERS));
.tab("Icon").range(1, AbilityIconData.MAX_LAYERS).visibleWhen(isCustomIcon));
for (int i = 0; i < AbilityIconData.MAX_LAYERS; i++) {
final int idx = i;
java.util.function.BooleanSupplier layerVisible = () -> chainIcon.getLayerCount() > idx;
java.util.function.BooleanSupplier layerVisible = () -> isCustomIcon.getAsBoolean() && chainIcon.getLayerCount() > idx;
String sectionLabel = net.minecraft.util.StatCollector.translateToLocal("ability.icon.layer") + " " + (idx + 1);
fieldDefs.add(FieldDef.section(sectionLabel).tab("Icon").visibleWhen(layerVisible));
fieldDefs.add(FieldDef.textureSubGui("gui.texture",
@@ -194,12 +203,12 @@ public class SubGuiChainedAbilityConfig extends SubGuiInterface implements IText
}
// Animation
fieldDefs.add(FieldDef.section("Animation").tab("Icon"));
fieldDefs.add(FieldDef.boolField("gui.animated", chainIcon::isAnimated, chainIcon::setAnimated).tab("Icon").hover("gui.animated.hover"));
fieldDefs.add(FieldDef.section("Animation").tab("Icon").visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.boolField("gui.animated", chainIcon::isAnimated, chainIcon::setAnimated).tab("Icon").hover("gui.animated.hover").visibleWhen(isCustomIcon));
fieldDefs.add(FieldDef.intField("gui.frameCount", chainIcon::getFrameCount, chainIcon::setFrameCount)
.tab("Icon").range(1, 256).visibleWhen(chainIcon::isAnimated));
.tab("Icon").range(1, 256).visibleWhen(() -> isCustomIcon.getAsBoolean() && chainIcon.isAnimated()));
fieldDefs.add(FieldDef.intField("gui.frameTime", chainIcon::getFrameTime, chainIcon::setFrameTime)
.tab("Icon").range(1, 100).visibleWhen(chainIcon::isAnimated));
.tab("Icon").range(1, 100).visibleWhen(() -> isCustomIcon.getAsBoolean() && chainIcon.isAnimated()));
// External field providers (e.g., DBC Addon injecting a "DBC" tab)
if (AbilityController.Instance != null) {
@@ -3,6 +3,8 @@ package noppes.npcs.client.gui.advanced;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiButton;
import kamkeel.npcs.controllers.data.ability.conditions.ConditionHasEffect;
import noppes.npcs.client.gui.builder.FieldDef;
import noppes.npcs.client.gui.util.GuiCustomScroll;
import noppes.npcs.client.gui.util.GuiNpcButton;
import noppes.npcs.client.gui.util.GuiNpcTextField;
@@ -25,6 +27,23 @@ import java.util.Map;
@SideOnly(Side.CLIENT)
public class SubGuiCustomEffectSelect extends SubGuiInterface implements ICustomScrollListener, ITextfieldListener {
public static FieldDef createSelectField(ConditionHasEffect condition) {
return FieldDef.subGuiField("condition.select_effect",
() -> new SubGuiCustomEffectSelect(condition.getEffectId(), condition.getEffectIndex()),
gui -> {
SubGuiCustomEffectSelect sel = (SubGuiCustomEffectSelect) gui;
if (sel.getSelectedEffectId() >= 0) {
condition.setEffect(sel.getSelectedEffectId(), sel.getSelectedIndex());
}
})
.buttonLabel(() -> {
if (condition.getEffectId() < 0) return "None";
CustomEffect effect = condition.getEffect();
return effect != null ? effect.getName() : "ID:" + condition.getEffectId();
})
.clearable(() -> condition.setEffect(-1, 0));
}
private GuiCustomScroll scroll;
private final HashMap<String, Integer> displayNameToId = new HashMap<>();
private final HashMap<String, Integer> allDisplayNameToId = new HashMap<>();
@@ -39,6 +39,7 @@ public class QuestTrackingComponent extends HudComponent {
if (turnIn != null && !turnIn.isEmpty()) {
turnInLines.add(convertColorCodes(turnIn));
}
updateOverlayHeight();
}
/**
@@ -239,6 +240,19 @@ public class QuestTrackingComponent extends HudComponent {
}
// ---------- Helper rendering methods ----------- (methods unchanged) ...
private void updateOverlayHeight() {
int lineHeight = mc.fontRenderer.FONT_HEIGHT + 4;
int contentHeight = 5;
contentHeight += questTitleLines.size() * lineHeight + 8;
contentHeight += questCategoryLines.size() * lineHeight + 8;
contentHeight += objectiveLines.size() * lineHeight;
if (!turnInLines.isEmpty()) {
contentHeight += 8;
}
contentHeight += turnInLines.size() * lineHeight;
overlayHeight = contentHeight;
}
private int renderTextBlock(List<String> lines, int startY, int align, int color) {
int y = startY;
FontRenderer font = mc.fontRenderer;
@@ -4,6 +4,7 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.packets.player.ability.AbilityHotbarSelectPacket;
@@ -638,9 +639,12 @@ public class AbilityHotbarComponent extends HudComponent {
String key = slots[slotIndex].abilityKey;
Ability ability = slots[slotIndex].ability;
IAbilityAction action = slots[slotIndex].action;
if (ability != null && ability.isPerAbilityCooldown()) {
return playerData.abilityData.getPerAbilityCooldownProgress(key);
} else if (action instanceof ChainedAbility && ((ChainedAbility) action).isPerAbilityCooldown()) {
return playerData.abilityData.getPerAbilityCooldownProgress(key);
} else {
return playerData.abilityData.getGlobalCooldownProgress();
}
@@ -58,9 +58,12 @@ public class GuiNpcAnvil extends GuiContainerNPCInterface {
// Compute the repair status message based on container.repairCost and player's XP.
String status = "";
int textColor = CustomNpcResourceListener.DefaultTextColor;
if (container.repairCost > 0) {
if (container.repairCost > mc.thePlayer.experienceTotal) {
status = "Repair cost: " + container.repairCost + " XP";
textColor = 0xFF0000; // red when not enough XP
} else {
status = "Repair cost: " + container.repairCost + " XP";
}
@@ -72,10 +75,6 @@ public class GuiNpcAnvil extends GuiContainerNPCInterface {
status = "Item is already fully repaired";
}
}
int textColor = CustomNpcResourceListener.DefaultTextColor;
if (container.repairCost > mc.thePlayer.experienceTotal) {
textColor = 0xFF0000; // red when not enough XP
}
fontRendererObj.drawString(status, guiLeft + 5, guiTop + 75, textColor);
}
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more