"));
+ return;
+ }
+
+ String type = args[0].toLowerCase();
+ boolean newState = CNPCDebug.toggleClient(type);
+ String stateText = newState ? "\u00A7aENABLED" : "\u00A7cDISABLED";
+ sender.addChatMessage(new ChatComponentText("\u00A77[CNPC+] \u00A7eClient debug '" + type + "' " + stateText));
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/EnergyChargePreviewRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/EnergyChargePreviewRenderer.java
new file mode 100644
index 000000000..66bf4869b
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/EnergyChargePreviewRenderer.java
@@ -0,0 +1,38 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.common.eventhandler.SubscribeEvent;
+import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
+import kamkeel.npcs.entity.EntityEnergyProjectile;
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.renderer.entity.RenderManager;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraftforge.client.event.RenderWorldLastEvent;
+
+/**
+ * Renders packet-driven charging previews through RenderManager.
+ */
+public class EnergyChargePreviewRenderer {
+
+ @SubscribeEvent
+ public void onRenderWorldLast(RenderWorldLastEvent event) {
+ if (EnergyChargePreviewManager.ClientInstance == null || !EnergyChargePreviewManager.ClientInstance.hasPreviews()) {
+ return;
+ }
+
+ Minecraft mc = Minecraft.getMinecraft();
+ EntityPlayer player = mc.thePlayer;
+ if (player == null) return;
+
+ float partialTicks = event.partialTicks;
+
+ for (EntityEnergyProjectile entity : EnergyChargePreviewManager.ClientInstance.getPreviews()) {
+ if (entity == null || entity.isDead) continue;
+
+ double x = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks - RenderManager.renderPosX;
+ double y = entity.prevPosY + (entity.posY - entity.prevPosY) * partialTicks - RenderManager.renderPosY;
+ double z = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks - RenderManager.renderPosZ;
+
+ RenderManager.instance.renderEntityWithPosYaw(entity, x, y, z, entity.rotationYaw, partialTicks);
+ }
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java b/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java
deleted file mode 100644
index 96e8e7b08..000000000
--- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityProjectile.java
+++ /dev/null
@@ -1,259 +0,0 @@
-package kamkeel.npcs.client.renderer;
-
-import cpw.mods.fml.relauncher.Side;
-import cpw.mods.fml.relauncher.SideOnly;
-import net.minecraft.client.renderer.OpenGlHelper;
-import net.minecraft.client.renderer.Tessellator;
-import net.minecraft.client.renderer.entity.Render;
-import net.minecraft.entity.Entity;
-import net.minecraft.util.ResourceLocation;
-import org.lwjgl.opengl.GL11;
-import org.lwjgl.opengl.GL12;
-
-/**
- * Base renderer for ability projectiles.
- * Provides common GL state setup and rendering utilities.
- *
- * Design inspired by LouisXIV's energy rendering system.
- */
-@SideOnly(Side.CLIENT)
-public abstract class RenderAbilityProjectile extends Render {
-
- protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png");
-
- public RenderAbilityProjectile() {
- this.shadowSize = 0.0f;
- }
-
- /**
- * Setup GL state for translucent, self-illuminated rendering.
- * Forces full brightness so world lighting does not affect projectiles.
- */
- protected void setupRenderState() {
- GL11.glPushMatrix();
- GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
- GL11.glDisable(GL11.GL_CULL_FACE);
- GL11.glEnable(GL12.GL_RESCALE_NORMAL);
- GL11.glEnable(GL11.GL_ALPHA_TEST);
- GL11.glEnable(GL11.GL_BLEND);
- GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
- GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F);
- GL11.glDisable(GL11.GL_LIGHTING);
- GL11.glDisable(GL11.GL_TEXTURE_2D);
-
- // Force full brightness - prevents world lighting from darkening projectiles
- OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
- }
-
- /**
- * Restore GL state after rendering.
- */
- protected void restoreRenderState() {
- GL11.glPopAttrib();
- GL11.glPopMatrix();
- }
-
- /**
- * Extract RGB components from color int.
- */
- protected float[] extractRGB(int color) {
- float r = ((color >> 16) & 0xFF) / 255.0f;
- float g = ((color >> 8) & 0xFF) / 255.0f;
- float b = (color & 0xFF) / 255.0f;
- return new float[]{r, g, b};
- }
-
- /**
- * Render a cube centered at origin with given color and alpha.
- */
- protected void renderCube(int color, float alpha, float halfSize) {
- float[] rgb = extractRGB(color);
- float r = rgb[0], g = rgb[1], b = rgb[2];
-
- Tessellator tess = Tessellator.instance;
-
- // Front face (z+)
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(0, 0, 1);
- tess.addVertex(-halfSize, -halfSize, halfSize);
- tess.addVertex(halfSize, -halfSize, halfSize);
- tess.addVertex(halfSize, halfSize, halfSize);
- tess.addVertex(-halfSize, halfSize, halfSize);
- tess.draw();
-
- // Back face (z-)
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(0, 0, -1);
- tess.addVertex(halfSize, -halfSize, -halfSize);
- tess.addVertex(-halfSize, -halfSize, -halfSize);
- tess.addVertex(-halfSize, halfSize, -halfSize);
- tess.addVertex(halfSize, halfSize, -halfSize);
- tess.draw();
-
- // Top face (y+)
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(0, 1, 0);
- tess.addVertex(-halfSize, halfSize, halfSize);
- tess.addVertex(halfSize, halfSize, halfSize);
- tess.addVertex(halfSize, halfSize, -halfSize);
- tess.addVertex(-halfSize, halfSize, -halfSize);
- tess.draw();
-
- // Bottom face (y-)
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(0, -1, 0);
- tess.addVertex(-halfSize, -halfSize, -halfSize);
- tess.addVertex(halfSize, -halfSize, -halfSize);
- tess.addVertex(halfSize, -halfSize, halfSize);
- tess.addVertex(-halfSize, -halfSize, halfSize);
- tess.draw();
-
- // Right face (x+)
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(1, 0, 0);
- tess.addVertex(halfSize, -halfSize, halfSize);
- tess.addVertex(halfSize, -halfSize, -halfSize);
- tess.addVertex(halfSize, halfSize, -halfSize);
- tess.addVertex(halfSize, halfSize, halfSize);
- tess.draw();
-
- // Left face (x-)
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(-1, 0, 0);
- tess.addVertex(-halfSize, -halfSize, -halfSize);
- tess.addVertex(-halfSize, -halfSize, halfSize);
- tess.addVertex(-halfSize, halfSize, halfSize);
- tess.addVertex(-halfSize, halfSize, -halfSize);
- tess.draw();
- }
-
- /**
- * Render a flat disc (cylinder with very small height) centered at origin.
- * The disc lies flat on the XZ plane.
- */
- protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) {
- float[] rgb = extractRGB(color);
- float r = rgb[0], g = rgb[1], b = rgb[2];
-
- Tessellator tess = Tessellator.instance;
- float halfThick = thickness * 0.5f;
-
- // Top face
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(0, 1, 0);
- for (int i = 0; i < segments; i++) {
- float angle1 = (float) (2 * Math.PI * i / segments);
- float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
- float x1 = (float) Math.cos(angle1) * radius;
- float z1 = (float) Math.sin(angle1) * radius;
- float x2 = (float) Math.cos(angle2) * radius;
- float z2 = (float) Math.sin(angle2) * radius;
-
- tess.addVertex(0, halfThick, 0);
- tess.addVertex(x1, halfThick, z1);
- tess.addVertex(x2, halfThick, z2);
- tess.addVertex(0, halfThick, 0);
- }
- tess.draw();
-
- // Bottom face
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.setNormal(0, -1, 0);
- for (int i = 0; i < segments; i++) {
- float angle1 = (float) (2 * Math.PI * i / segments);
- float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
- float x1 = (float) Math.cos(angle1) * radius;
- float z1 = (float) Math.sin(angle1) * radius;
- float x2 = (float) Math.cos(angle2) * radius;
- float z2 = (float) Math.sin(angle2) * radius;
-
- tess.addVertex(0, -halfThick, 0);
- tess.addVertex(x2, -halfThick, z2);
- tess.addVertex(x1, -halfThick, z1);
- tess.addVertex(0, -halfThick, 0);
- }
- tess.draw();
-
- // Edge
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- for (int i = 0; i < segments; i++) {
- float angle1 = (float) (2 * Math.PI * i / segments);
- float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
- float x1 = (float) Math.cos(angle1) * radius;
- float z1 = (float) Math.sin(angle1) * radius;
- float x2 = (float) Math.cos(angle2) * radius;
- float z2 = (float) Math.sin(angle2) * radius;
-
- // Normal pointing outward
- float nx = (float) Math.cos((angle1 + angle2) * 0.5);
- float nz = (float) Math.sin((angle1 + angle2) * 0.5);
- tess.setNormal(nx, 0, nz);
-
- tess.addVertex(x1, -halfThick, z1);
- tess.addVertex(x2, -halfThick, z2);
- tess.addVertex(x2, halfThick, z2);
- tess.addVertex(x1, halfThick, z1);
- }
- tess.draw();
- }
-
- /**
- * Render a line segment as a quad billboard facing the camera.
- */
- protected void renderLineSegment(double x1, double y1, double z1,
- double x2, double y2, double z2,
- float width, int color, float alpha) {
- float[] rgb = extractRGB(color);
- float r = rgb[0], g = rgb[1], b = rgb[2];
-
- // Calculate direction
- double dx = x2 - x1;
- double dy = y2 - y1;
- double dz = z2 - z1;
- double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
- if (len < 0.001) return;
-
- // Perpendicular vectors for billboard
- double perpX, perpY, perpZ;
- if (Math.abs(dy) < 0.9) {
- // Cross with up vector
- perpX = -dz;
- perpY = 0;
- perpZ = dx;
- } else {
- // Cross with right vector
- perpX = 0;
- perpY = dz;
- perpZ = -dy;
- }
- double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
- if (perpLen > 0) {
- perpX = perpX / perpLen * width * 0.5;
- perpY = perpY / perpLen * width * 0.5;
- perpZ = perpZ / perpLen * width * 0.5;
- }
-
- Tessellator tess = Tessellator.instance;
- tess.startDrawingQuads();
- tess.setColorRGBA_F(r, g, b, alpha);
- tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ);
- tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ);
- tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ);
- tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ);
- tess.draw();
- }
-
- @Override
- protected ResourceLocation getEntityTexture(Entity entity) {
- return WHITE_TEXTURE;
- }
-}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java
new file mode 100644
index 000000000..980293c17
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergy.java
@@ -0,0 +1,410 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
+import kamkeel.npcs.entity.EntityEnergyAbility;
+import kamkeel.npcs.entity.EntityEnergyProjectile;
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.renderer.OpenGlHelper;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.client.renderer.entity.Render;
+import net.minecraft.entity.Entity;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.util.ResourceLocation;
+import noppes.npcs.config.ConfigClient;
+import org.lwjgl.opengl.GL11;
+import org.lwjgl.opengl.GL12;
+
+/**
+ * Base renderer for ability projectiles.
+ * Provides common GL state setup and rendering utilities.
+ *
+ * Design inspired by LouisXIV's energy rendering system.
+ */
+@SideOnly(Side.CLIENT)
+public abstract class RenderEnergy extends Render {
+
+ protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png");
+ protected static final int HIDE_INITIAL_ACTIVE_TICKS = 1;
+
+ public RenderEnergy() {
+ this.shadowSize = 0.0f;
+ }
+
+ /**
+ * Hide the first active tick to avoid the visible spawn-frame pause at fire time.
+ * Charging previews are never hidden.
+ */
+ protected boolean shouldSkipInitialActiveRender(Entity entity) {
+ if (!(entity instanceof EntityEnergyAbility)) return false;
+ EntityEnergyAbility ability = (EntityEnergyAbility) entity;
+ return !ability.isPreviewMode() && !ability.isCharging() && ability.ticksExisted <= HIDE_INITIAL_ACTIVE_TICKS;
+ }
+
+ /**
+ * Setup GL state for translucent, self-illuminated rendering.
+ * Forces full brightness so world lighting does not affect projectiles.
+ */
+ protected void setupRenderState() {
+ GL11.glPushMatrix();
+ GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
+ GL11.glDisable(GL11.GL_CULL_FACE);
+ GL11.glEnable(GL12.GL_RESCALE_NORMAL);
+ GL11.glEnable(GL11.GL_ALPHA_TEST);
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+ GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F);
+ GL11.glDisable(GL11.GL_LIGHTING);
+ GL11.glDisable(GL11.GL_TEXTURE_2D);
+
+ // Force full brightness - prevents world lighting from darkening projectiles
+ OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
+ }
+
+ /**
+ * Restore GL state after rendering.
+ */
+ protected void restoreRenderState() {
+ GL11.glPopAttrib();
+ GL11.glPopMatrix();
+ }
+
+ /**
+ * Extract RGB components from color int.
+ */
+ protected float[] extractRGB(int color) {
+ float r = ((color >> 16) & 0xFF) / 255.0f;
+ float g = ((color >> 8) & 0xFF) / 255.0f;
+ float b = (color & 0xFF) / 255.0f;
+ return new float[]{r, g, b};
+ }
+
+ /**
+ * Render a cube centered at origin with given color and alpha.
+ */
+ protected void renderCube(int color, float alpha, float halfSize) {
+ Tessellator tess = Tessellator.instance;
+ float r = ((color >> 16) & 0xFF) / 255.0f;
+ float g = ((color >> 8) & 0xFF) / 255.0f;
+ float b = (color & 0xFF) / 255.0f;
+
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ addCubeVertices(tess, 0, 0, 0, halfSize);
+ tess.draw();
+ }
+
+ // ==================== BATCHED CUBE RENDERING ====================
+
+ /**
+ * Begin a batched cube draw call. All cubes added via {@link #addBatchedCube}
+ * will be drawn in a single tessellator pass when {@link #endCubeBatch} is called.
+ */
+ protected void beginCubeBatch() {
+ Tessellator.instance.startDrawingQuads();
+ }
+
+ /**
+ * Add a cube to the current batch at the given position with per-cube color/alpha.
+ * Must be called between {@link #beginCubeBatch} and {@link #endCubeBatch}.
+ */
+ protected void addBatchedCube(float px, float py, float pz, float halfSize,
+ float r, float g, float b, float alpha) {
+ Tessellator tess = Tessellator.instance;
+ tess.setColorRGBA_F(r, g, b, alpha);
+ addCubeVertices(tess, px, py, pz, halfSize);
+ }
+
+ /**
+ * End the batched cube draw call, flushing all queued cubes in one draw.
+ */
+ protected void endCubeBatch() {
+ Tessellator.instance.draw();
+ }
+
+ /**
+ * Add the 24 vertices (6 faces) of a cube centered at (px,py,pz) to the tessellator.
+ * Color must be set before calling. Used by both single and batched cube rendering.
+ */
+ private static void addCubeVertices(Tessellator tess, float px, float py, float pz, float h) {
+ float x0 = px - h, x1 = px + h;
+ float y0 = py - h, y1 = py + h;
+ float z0 = pz - h, z1 = pz + h;
+
+ // Front (z+)
+ tess.setNormal(0, 0, 1);
+ tess.addVertex(x0, y0, z1);
+ tess.addVertex(x1, y0, z1);
+ tess.addVertex(x1, y1, z1);
+ tess.addVertex(x0, y1, z1);
+
+ // Back (z-)
+ tess.setNormal(0, 0, -1);
+ tess.addVertex(x1, y0, z0);
+ tess.addVertex(x0, y0, z0);
+ tess.addVertex(x0, y1, z0);
+ tess.addVertex(x1, y1, z0);
+
+ // Top (y+)
+ tess.setNormal(0, 1, 0);
+ tess.addVertex(x0, y1, z1);
+ tess.addVertex(x1, y1, z1);
+ tess.addVertex(x1, y1, z0);
+ tess.addVertex(x0, y1, z0);
+
+ // Bottom (y-)
+ tess.setNormal(0, -1, 0);
+ tess.addVertex(x0, y0, z0);
+ tess.addVertex(x1, y0, z0);
+ tess.addVertex(x1, y0, z1);
+ tess.addVertex(x0, y0, z1);
+
+ // Right (x+)
+ tess.setNormal(1, 0, 0);
+ tess.addVertex(x1, y0, z1);
+ tess.addVertex(x1, y0, z0);
+ tess.addVertex(x1, y1, z0);
+ tess.addVertex(x1, y1, z1);
+
+ // Left (x-)
+ tess.setNormal(-1, 0, 0);
+ tess.addVertex(x0, y0, z0);
+ tess.addVertex(x0, y0, z1);
+ tess.addVertex(x0, y1, z1);
+ tess.addVertex(x0, y1, z0);
+ }
+
+ /**
+ * Render a flat disc (cylinder with very small height) centered at origin.
+ * The disc lies flat on the XZ plane.
+ */
+ protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) {
+ float[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+
+ Tessellator tess = Tessellator.instance;
+ float halfThick = thickness * 0.5f;
+
+ // Top face
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(0, 1, 0);
+ for (int i = 0; i < segments; i++) {
+ float angle1 = (float) (2 * Math.PI * i / segments);
+ float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
+ float x1 = (float) Math.cos(angle1) * radius;
+ float z1 = (float) Math.sin(angle1) * radius;
+ float x2 = (float) Math.cos(angle2) * radius;
+ float z2 = (float) Math.sin(angle2) * radius;
+
+ tess.addVertex(0, halfThick, 0);
+ tess.addVertex(x1, halfThick, z1);
+ tess.addVertex(x2, halfThick, z2);
+ tess.addVertex(0, halfThick, 0);
+ }
+ tess.draw();
+
+ // Bottom face
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(0, -1, 0);
+ for (int i = 0; i < segments; i++) {
+ float angle1 = (float) (2 * Math.PI * i / segments);
+ float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
+ float x1 = (float) Math.cos(angle1) * radius;
+ float z1 = (float) Math.sin(angle1) * radius;
+ float x2 = (float) Math.cos(angle2) * radius;
+ float z2 = (float) Math.sin(angle2) * radius;
+
+ tess.addVertex(0, -halfThick, 0);
+ tess.addVertex(x2, -halfThick, z2);
+ tess.addVertex(x1, -halfThick, z1);
+ tess.addVertex(0, -halfThick, 0);
+ }
+ tess.draw();
+
+ // Edge
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ for (int i = 0; i < segments; i++) {
+ float angle1 = (float) (2 * Math.PI * i / segments);
+ float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
+ float x1 = (float) Math.cos(angle1) * radius;
+ float z1 = (float) Math.sin(angle1) * radius;
+ float x2 = (float) Math.cos(angle2) * radius;
+ float z2 = (float) Math.sin(angle2) * radius;
+
+ // Normal pointing outward
+ float nx = (float) Math.cos((angle1 + angle2) * 0.5);
+ float nz = (float) Math.sin((angle1 + angle2) * 0.5);
+ tess.setNormal(nx, 0, nz);
+
+ tess.addVertex(x1, -halfThick, z1);
+ tess.addVertex(x2, -halfThick, z2);
+ tess.addVertex(x2, halfThick, z2);
+ tess.addVertex(x1, halfThick, z1);
+ }
+ tess.draw();
+ }
+
+ /**
+ * Render a line segment as a quad billboard facing the camera.
+ */
+ protected void renderLineSegment(double x1, double y1, double z1,
+ double x2, double y2, double z2,
+ float width, int color, float alpha) {
+ float[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+
+ // Calculate direction
+ double dx = x2 - x1;
+ double dy = y2 - y1;
+ double dz = z2 - z1;
+ double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
+ if (len < 0.001) return;
+
+ // Perpendicular vectors for billboard
+ double perpX, perpY, perpZ;
+ if (Math.abs(dy) < 0.9) {
+ // Cross with up vector
+ perpX = -dz;
+ perpY = 0;
+ perpZ = dx;
+ } else {
+ // Cross with right vector
+ perpX = 0;
+ perpY = dz;
+ perpZ = -dy;
+ }
+ double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
+ if (perpLen > 0) {
+ perpX = perpX / perpLen * width * 0.5;
+ perpY = perpY / perpLen * width * 0.5;
+ perpZ = perpZ / perpLen * width * 0.5;
+ }
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ);
+ tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ);
+ tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ);
+ tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ);
+ tess.draw();
+ }
+
+ // ==================== SHARED LIGHTNING ====================
+
+ /**
+ * Get or create the lightning state for an energy entity.
+ * Uses the lightningState field on EntityEnergyAbility (stored as Object
+ * to avoid client class loading on server).
+ */
+ protected AttachedLightningRenderer.LightningState getLightningState(EntityEnergyAbility entity) {
+ if (entity.lightningState == null) {
+ entity.lightningState = new AttachedLightningRenderer.LightningState();
+ }
+ return (AttachedLightningRenderer.LightningState) entity.lightningState;
+ }
+
+ /**
+ * Render attached lightning arcs around an energy entity.
+ *
+ * @param entity the energy entity
+ * @param innerScale multiplier for inner radius (e.g. 0.3f for projectiles, 0.95f for dome)
+ * @param baseSize the entity's current render size/scale
+ */
+ protected void renderAttachedLightning(EntityEnergyAbility entity, float innerScale, float baseSize) {
+ AttachedLightningRenderer.LightningState state = getLightningState(entity);
+
+ float density = entity.getLightningDensity();
+ float innerRadius = innerScale * baseSize;
+ float radius = innerRadius + entity.getLightningRadius() * baseSize;
+ int outerColor = entity.getOuterColor();
+ int innerColor = entity.getInnerColor();
+ int fadeTime = entity.getLightningFadeTime();
+
+ // Barrier impact spark: briefly force brighter white crackles at the contact point.
+ if (entity instanceof EntityEnergyProjectile) {
+ int sparkTicks = ((EntityEnergyProjectile) entity).getBarrierSparkTicks();
+ if (sparkTicks > 0) {
+ density = Math.max(density, 4.0f + sparkTicks * 0.6f);
+ radius = Math.max(radius, innerRadius + Math.max(0.35f, baseSize * 0.65f));
+ outerColor = 0xF0F6FF;
+ innerColor = 0xFFFFFF;
+ fadeTime = Math.max(fadeTime, 6);
+ }
+ }
+
+ state.update(density, radius, outerColor, innerColor, fadeTime);
+ state.render();
+ }
+
+ // ==================== PROXIMITY ALPHA ====================
+
+ /**
+ * Calculate a proximity-based alpha multiplier for owner's energy projectiles.
+ * Returns a factor between ProximityAlphaMin and 1.0 based on:
+ * - Distance from camera (close = faded, far = full)
+ * - Entity age (young = faded, old = full; ignored while charging)
+ *
+ * Only applies to the owning player's client. Non-owners always get 1.0.
+ *
+ * @param entity the energy projectile entity
+ * @param x camera-relative X (from doRender)
+ * @param y camera-relative Y (from doRender)
+ * @param z camera-relative Z (from doRender)
+ * @return alpha multiplier between ProximityAlphaMin and 1.0
+ */
+ protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z) {
+ return getProximityAlphaFactor(entity, x, y, z, false);
+ }
+
+ /**
+ * Overload that allows forcing proximity-only fade (no age fade-out).
+ * Used for attached beams and lasers that stay connected to the owner.
+ *
+ * @param alwaysUseProximity if true, age factor is ignored (proximity fade never expires)
+ */
+ protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z, boolean alwaysUseProximity) {
+ float minAlpha = ConfigClient.ProximityAlphaMin;
+ if (minAlpha >= 1.0f) return 1.0f;
+
+ // Only apply to the owner's client
+ EntityPlayer player = Minecraft.getMinecraft().thePlayer;
+ if (player == null || entity.getOwnerEntityId() != player.getEntityId()) {
+ return 1.0f;
+ }
+
+ // Distance factor: ramp from minAlpha at 0 to 1.0 at maxDist
+ float maxDist = ConfigClient.ProximityAlphaDistance;
+ float dist = (float) Math.sqrt(x * x + y * y + z * z);
+ float distFactor = Math.min(1.0f, dist / maxDist);
+
+ // Age factor: ramp from 0 to 1.0 over ageTicks
+ // Charging, attached beams/lasers, and alwaysUseProximity skip age fade
+ float ageFactor;
+ if (entity.isCharging() || alwaysUseProximity) {
+ ageFactor = 0.0f; // Always apply full proximity fade
+ } else {
+ int ageTicks = ConfigClient.ProximityAlphaAgeTicks;
+ if (ageTicks <= 0) {
+ ageFactor = 1.0f; // Age fade disabled
+ } else {
+ ageFactor = Math.min(1.0f, (float) entity.ticksExisted / ageTicks);
+ }
+ }
+
+ // Combined: take the max of both factors (either being far OR being old restores alpha)
+ float combinedFactor = Math.max(distFactor, ageFactor);
+
+ // Lerp between minAlpha and 1.0
+ return minAlpha + (1.0f - minAlpha) * combinedFactor;
+ }
+
+ @Override
+ protected ResourceLocation getEntityTexture(Entity entity) {
+ return WHITE_TEXTURE;
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java
new file mode 100644
index 000000000..846c167ea
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBarrier.java
@@ -0,0 +1,23 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.entity.EntityEnergyBarrier;
+
+/**
+ * Intermediate renderer base for energy barrier entities (Dome, Panel).
+ * Provides shared hit flash alpha computation.
+ */
+@SideOnly(Side.CLIENT)
+public abstract class RenderEnergyBarrier extends RenderEnergy {
+
+ /**
+ * Compute the alpha boost from a hit flash effect.
+ * Flash value decays from 4 to 0, producing alpha from 0.3 to 0.
+ */
+ protected float computeFlashAlpha(EntityEnergyBarrier barrier) {
+ byte flash = barrier.getHitFlash();
+ if (flash <= 0) return 0.0f;
+ return flash / 4.0f * 0.3f;
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java
similarity index 85%
rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java
rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java
index 4912e4b72..decd15ef8 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityBeam.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java
@@ -2,9 +2,9 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
-import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityBeam;
import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import org.lwjgl.opengl.GL11;
@@ -15,26 +15,32 @@ import java.util.List;
/**
* Renders the AbilityBeam entity with a head, tail orb, and curving trail.
* The trail shows the path the head has traveled using laser-style rectangular segments.
- *
+ *
* IMPORTANT: Trail points are stored RELATIVE to the origin position.
* We render by translating to the origin first, then drawing all points relative to that.
- *
+ *
* Trail segments now share vertices at connection points to prevent gaps during curves.
- *
+ *
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
-public class RenderAbilityBeam extends RenderAbilityProjectile {
+public class RenderEnergyBeam extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ if (shouldSkipInitialActiveRender(entity)) {
+ return;
+ }
EntityAbilityBeam beam = (EntityAbilityBeam) entity;
setupRenderState();
+ // Proximity alpha fade for owner (attached beams always use proximity, never age out)
+ float proximityAlpha = getProximityAlphaFactor(beam, x, y, z, beam.isAttachedToOwner());
+
// Handle charging state (windup phase) - render only growing orb
if (beam.isCharging()) {
- renderChargingOrb(beam, x, y, z, partialTicks);
+ renderChargingOrb(beam, x, y, z, partialTicks, proximityAlpha);
restoreRenderState();
return;
}
@@ -46,24 +52,25 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
return;
}
- // Get interpolated head offset
+ // Get interpolated head offset (for head/trail rendering relative to origin)
double headOffsetX = beam.getInterpolatedHeadOffsetX(partialTicks);
double headOffsetY = beam.getInterpolatedHeadOffsetY(partialTicks);
double headOffsetZ = beam.getInterpolatedHeadOffsetZ(partialTicks);
- // The render system passes x,y,z as the position to render the entity at
- // Entity position = origin + headOffset (in world coords)
- // So origin render position = x,y,z - headOffset
- double renderOriginX = x - headOffsetX;
- double renderOriginY = y - headOffsetY;
- double renderOriginZ = z - headOffsetZ;
+ // Compute render origin directly from the world origin and camera position.
+ // We can't derive it from MC's x,y,z because syncPositionStateToCurrent() snaps
+ // lastTickPos = posX on every sync packet, killing MC's position interpolation.
+ // The headOffset interpolation then mismatches, causing the origin to wobble.
+ double renderOriginX = beam.getOriginX() - RenderManager.renderPosX;
+ double renderOriginY = beam.getOriginY() - RenderManager.renderPosY;
+ double renderOriginZ = beam.getOriginZ() - RenderManager.renderPosZ;
- // Get beam properties
- float beamWidth = beam.getBeamWidth();
- float headSize = beam.getHeadSize();
+ // Get beam properties (lerp-smoothed for smooth size transitions)
+ float beamWidth = beam.getInterpolatedBeamWidth(partialTicks);
+ float headSize = beam.getInterpolatedHeadSize(partialTicks);
int innerColor = beam.getInnerColor();
int outerColor = beam.getOuterColor();
- float outerAlpha = beam.getOuterColorAlpha();
+ float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
// Render everything relative to origin position
GL11.glPushMatrix();
@@ -72,21 +79,24 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Calculate head distance from origin (for overlap check)
double headDistFromOrigin = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ);
- // Render tail orb at origin (0,0,0) - only in anchored mode
- // Don't render if head is too close to origin (would cause overlap/extra orb appearance)
- if (beam.shouldRenderTailOrb() && headDistFromOrigin > headSize * 0.5) {
- renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha);
+ float innerAlpha = beam.getInnerAlpha() * proximityAlpha;
+
+ // Render trail segments first (with fading for non-anchored)
+ if (beam.hasFadingTrail()) {
+ renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
+ } else {
+ renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
}
- // Render trail segments with smooth connections (with fading for non-anchored)
- if (beam.hasFadingTrail()) {
- renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth());
- } else {
- renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth());
+ // Render tail orb at origin (0,0,0) AFTER trail so it draws on top
+ // Don't render if head is too close to origin (would cause overlap/extra orb appearance)
+ // Use target headSize (not lerped) so the threshold isn't inflated by lerp lag
+ if (beam.shouldRenderTailOrb() && headDistFromOrigin > beam.getHeadSize() * 0.5) {
+ renderTailOrb(beam.getHeadSize() * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, innerAlpha);
}
// Render head at interpolated offset position
- renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, partialTicks);
+ renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks);
GL11.glPopMatrix();
@@ -97,8 +107,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the charging orb during windup phase.
* Grows from 0 to headSize based on charge progress.
*/
- private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks) {
- float headSize = beam.getHeadSize();
+ private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks, float proximityAlpha) {
+ float headSize = beam.getInterpolatedHeadSize(partialTicks);
float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks);
float size = headSize * chargeProgress;
@@ -117,7 +127,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render lightning during charging if enabled
if (beam.hasLightningEffect()) {
- renderAttachedLightning(beam, scale);
+ renderAttachedLightning(beam, 0.6f * 0.5f, scale);
}
GL11.glPushMatrix();
@@ -129,7 +139,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render outer glow only if enabled
if (beam.isOuterColorEnabled()) {
float outerScale = innerScale + beam.getOuterColorWidth();
- float outerAlpha = beam.getOuterColorAlpha();
+ float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
@@ -140,7 +150,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
- renderCube(innerColor, 1.0f, 0.5f);
+ renderCube(innerColor, beam.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -150,7 +160,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the tail orb at the origin (where the beam emanates from).
* This orb does not rotate - it's a stable anchor point.
*/
- private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha) {
+ private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha, float innerAlpha) {
GL11.glPushMatrix();
// Already at origin (0,0,0)
@@ -172,7 +182,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core (solid)
GL11.glPushMatrix();
GL11.glScalef(size * innerScale, size * innerScale, size * innerScale);
- renderCube(innerColor, 1.0f, 0.5f);
+ renderCube(innerColor, innerAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -183,7 +193,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Uses averaged perpendicular vectors at connection points to prevent gaps.
*/
private void renderSmoothTrail(List trail, float width, int innerColor, int outerColor,
- boolean outerColorEnabled, float outerColorWidth) {
+ boolean outerColorEnabled, float outerColorWidth, float innerAlpha) {
if (trail.size() < 2) return;
int trailSize = trail.size();
@@ -206,7 +216,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
}
// Render inner core trail
- renderTrailTube(trail, perpFrames, innerWidth, innerColor, 0.9f, false);
+ renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false);
}
/**
@@ -214,7 +224,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Older trail points fade out based on their age.
*/
private void renderFadingTrail(EntityAbilityBeam beam, List trail, float width, int innerColor, int outerColor,
- boolean outerColorEnabled, float outerColorWidth) {
+ boolean outerColorEnabled, float outerColorWidth, float innerAlpha) {
if (trail.size() < 2) return;
List ages = beam.getTrailPointAges();
@@ -236,14 +246,14 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
}
// Render inner core trail with fading
- renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, 0.9f);
+ renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, innerAlpha);
}
/**
* Render trail tube with age-based fading.
*/
private void renderFadingTrailTube(List trail, List perpFrames, List ages,
- int fadeTime, float width, int color, float baseAlpha) {
+ int fadeTime, float width, int color, float baseAlpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
float halfWidth = width * 0.5f;
@@ -261,8 +271,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Calculate alpha based on age (older = more faded)
float age1 = i < ages.size() ? ages.get(i) : 0;
float age2 = (i + 1) < ages.size() ? ages.get(i + 1) : 0;
- float fade1 = 1.0f - Math.min(1.0f, age1 / fadeTime);
- float fade2 = 1.0f - Math.min(1.0f, age2 / fadeTime);
+ float fade1 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age1 / fadeTime)) : 0.0f;
+ float fade2 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age2 / fadeTime)) : 0.0f;
float alpha1 = baseAlpha * fade1;
float alpha2 = baseAlpha * fade2;
@@ -393,13 +403,17 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
dy /= len;
dz /= len;
} else {
- dx = 0; dy = 0; dz = 1;
+ dx = 0;
+ dy = 0;
+ dz = 1;
}
// Calculate perpendicular vectors using consistent up reference
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
- upX = 1; upY = 0; upZ = 0;
+ upX = 1;
+ upY = 0;
+ upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -418,8 +432,12 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
double vertY = dz * horzX - dx * horzZ;
double vertZ = dx * horzY - dy * horzX;
- frame[0] = horzX; frame[1] = horzY; frame[2] = horzZ;
- frame[3] = vertX; frame[4] = vertY; frame[5] = vertZ;
+ frame[0] = horzX;
+ frame[1] = horzY;
+ frame[2] = horzZ;
+ frame[3] = vertX;
+ frame[4] = vertY;
+ frame[5] = vertZ;
frames.add(frame);
}
@@ -430,7 +448,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the trail as a continuous tube using pre-computed perpendicular frames.
*/
private void renderTrailTube(List trail, List perpFrames,
- float width, int color, float baseAlpha, boolean fadeFromStart) {
+ float width, int color, float baseAlpha, boolean fadeFromStart) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
float halfWidth = width * 0.5f;
@@ -534,7 +552,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Coordinates are relative to origin.
*/
private void renderHead(EntityAbilityBeam beam, double x, double y, double z,
- float size, int innerColor, int outerColor, float outerAlpha, float partialTicks) {
+ float size, int innerColor, int outerColor, float outerAlpha, float innerAlpha, float partialTicks) {
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
@@ -545,7 +563,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions (only on head)
if (beam.hasLightningEffect()) {
- renderAttachedLightning(beam, scale);
+ renderAttachedLightning(beam, 0.6f * 0.5f, scale);
}
// Rotation
@@ -573,37 +591,10 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
- renderCube(innerColor, 1.0f, 0.5f);
+ renderCube(innerColor, innerAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
}
- /**
- * Render fading lightning arcs attached to the beam head (in local space).
- */
- private void renderAttachedLightning(EntityAbilityBeam beam, float headScale) {
- AttachedLightningRenderer.LightningState state = getLightningState(beam);
-
- float density = beam.getLightningDensity();
- // Lightning radius extends outward from inner surface (innerScale = 0.6)
- float innerRadius = 0.6f * headScale * 0.5f;
- float radius = innerRadius + beam.getLightningRadius() * headScale;
- int outerColor = beam.getOuterColor();
- int innerColor = beam.getInnerColor();
- int fadeTime = beam.getLightningFadeTime();
-
- state.update(density, radius, outerColor, innerColor, fadeTime);
- state.render();
- }
-
- /**
- * Get or create the lightning state for an entity.
- */
- private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityBeam beam) {
- if (beam.lightningState == null) {
- beam.lightningState = new AttachedLightningRenderer.LightningState();
- }
- return (AttachedLightningRenderer.LightningState) beam.lightningState;
- }
}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java
similarity index 76%
rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java
rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java
index 8cb8cdaad..93b90023e 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityDisc.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java
@@ -2,22 +2,26 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
-import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityDisc;
import net.minecraft.entity.Entity;
+import net.minecraft.util.Vec3;
+import noppes.npcs.util.MathUtil;
import org.lwjgl.opengl.GL11;
/**
* Renders the AbilityDisc entity as a flat spinning square.
* Rotates only on Y axis (flat spin like a saw blade).
- *
+ *
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
-public class RenderAbilityDisc extends RenderAbilityProjectile {
+public class RenderEnergyDisc extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ if (shouldSkipInitialActiveRender(entity)) {
+ return;
+ }
EntityAbilityDisc disc = (EntityAbilityDisc) entity;
setupRenderState();
@@ -27,8 +31,8 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
// Get interpolated values
float size = disc.getInterpolatedSize(partialTicks);
- float radius = disc.getDiscRadius() * size;
- float thickness = disc.getDiscThickness() * size;
+ float radius = disc.getInterpolatedDiscRadius(partialTicks) * size;
+ float thickness = disc.getInterpolatedDiscThickness(partialTicks) * size;
// Subtle pulsing effect
float pulseTime = entity.ticksExisted + partialTicks;
@@ -37,7 +41,7 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions
if (disc.hasLightningEffect()) {
- renderAttachedLightning(disc, radius * scale);
+ renderAttachedLightning(disc, 0.6f * 0.5f, radius * scale);
}
GL11.glPushMatrix();
@@ -52,23 +56,41 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
}
+ double motionX = entity.motionX;
+ double motionY = entity.motionY;
+ double motionZ = entity.motionZ;
+ double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
+
+ // Only apply motion-based facing when speed is meaningful.
+ // Near-zero motion makes atan2 unstable, producing jittery angles.
+ if (speedSq > 0.0001) {
+ Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
+ float motionYaw = MathUtil.getYaw(motionVec);
+ float motionPitch = MathUtil.getPitch(motionVec);
+ GL11.glRotatef(motionYaw, 0, 1, 0);
+ GL11.glRotatef(motionPitch, 1, 0, 0);
+ }
+
// Apply Y-axis rotation for spin
GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
// Inner scale defines the core size
float innerScale = 0.6f;
+ // Proximity alpha fade for owner
+ float proximityAlpha = getProximityAlphaFactor(disc, x, y, z);
+
// Render outer square (translucent) - only if enabled
// outerColorWidth is an additive offset from inner size
if (disc.isOuterColorEnabled()) {
float outerScale = innerScale + disc.getOuterColorWidth();
GL11.glDepthMask(false);
- renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha(), radius * outerScale, thickness);
+ renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha() * proximityAlpha, radius * outerScale, thickness);
GL11.glDepthMask(true);
}
// Render inner square (solid)
- renderFlatSquare(disc.getInnerColor(), 1.0f, radius * innerScale, thickness * 1.2f);
+ renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha() * proximityAlpha, radius * innerScale, thickness * 1.2f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -76,34 +98,6 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
restoreRenderState();
}
- /**
- * Render fading lightning arcs attached to the disc (in local space).
- */
- private void renderAttachedLightning(EntityAbilityDisc disc, float discSize) {
- AttachedLightningRenderer.LightningState state = getLightningState(disc);
-
- float density = disc.getLightningDensity();
- // Lightning radius extends outward from inner surface (innerScale = 0.6)
- float innerRadius = 0.6f * discSize * 0.5f;
- float radius = innerRadius + disc.getLightningRadius() * discSize;
- int outerColor = disc.getOuterColor();
- int innerColor = disc.getInnerColor();
- int fadeTime = disc.getLightningFadeTime();
-
- state.update(density, radius, outerColor, innerColor, fadeTime);
- state.render();
- }
-
- /**
- * Get or create the lightning state for an entity.
- */
- private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityDisc disc) {
- if (disc.lightningState == null) {
- disc.lightningState = new AttachedLightningRenderer.LightningState();
- }
- return (AttachedLightningRenderer.LightningState) disc.lightningState;
- }
-
/**
* Render a flat square (thin cube) centered at origin.
* The square lies flat on the XZ plane with thin Y height.
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java
new file mode 100644
index 000000000..34465635c
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDome.java
@@ -0,0 +1,111 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.entity.EntityEnergyDome;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.entity.Entity;
+import org.lwjgl.opengl.GL11;
+
+/**
+ * Renders the Dome entity as a translucent sphere.
+ * Inner layer solid, outer layer translucent glow.
+ */
+@SideOnly(Side.CLIENT)
+public class RenderEnergyDome extends RenderEnergyBarrier {
+
+ @Override
+ public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ if (shouldSkipInitialActiveRender(entity)) {
+ return;
+ }
+ EntityEnergyDome dome = (EntityEnergyDome) entity;
+ float radius = dome.getDomeRadius();
+ float healthPercent = dome.getHealthPercent();
+
+ setupRenderState();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Lightning BEFORE any rotation (uniform spread)
+ if (dome.hasLightningEffect()) {
+ renderAttachedLightning(dome, 0.95f, radius);
+ }
+
+ // Hit flash effect
+ float flashAlpha = computeFlashAlpha(dome);
+
+ float innerScale = 1.0f;
+
+ // Render outer dome (translucent glow)
+ if (dome.isOuterColorEnabled()) {
+ float outerScale = 1.0f + dome.getOuterColorWidth() * 0.1f;
+ float outerAlpha = dome.getOuterColorAlpha() * healthPercent;
+ GL11.glDepthMask(false);
+ renderSphere(dome.getOuterColor(), outerAlpha + (dome.getOuterColorAlpha() > 0 ? flashAlpha : 0), radius * outerScale, 8);
+ }
+
+ GL11.glDepthMask(true);
+ // Render inner dome (depth write enabled so inner sphere properly occludes)
+ renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8);
+ GL11.glPopMatrix();
+
+ restoreRenderState();
+ }
+
+ /**
+ * Render a sphere made of quad panels.
+ * Uses latitude/longitude segments to form a full sphere.
+ */
+ private void renderSphere(int color, float alpha, float radius, int segments) {
+ float[] rgb = extractRGB(color);
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(rgb[0], rgb[1], rgb[2], alpha);
+
+ for (int lat = 0; lat < segments; lat++) {
+ float theta1 = (float) (Math.PI * lat / segments - Math.PI * 0.5);
+ float theta2 = (float) (Math.PI * (lat + 1) / segments - Math.PI * 0.5);
+
+ float y1 = (float) Math.sin(theta1) * radius;
+ float y2 = (float) Math.sin(theta2) * radius;
+ float r1 = (float) Math.cos(theta1) * radius;
+ float r2 = (float) Math.cos(theta2) * radius;
+
+ for (int lon = 0; lon < segments; lon++) {
+ float phi1 = (float) (2 * Math.PI * lon / segments);
+ float phi2 = (float) (2 * Math.PI * (lon + 1) / segments);
+
+ float x1 = (float) Math.cos(phi1) * r1;
+ float z1 = (float) Math.sin(phi1) * r1;
+ float x2 = (float) Math.cos(phi2) * r1;
+ float z2 = (float) Math.sin(phi2) * r1;
+ float x3 = (float) Math.cos(phi2) * r2;
+ float z3 = (float) Math.sin(phi2) * r2;
+ float x4 = (float) Math.cos(phi1) * r2;
+ float z4 = (float) Math.sin(phi1) * r2;
+
+ float nx = (x1 + x2 + x3 + x4) * 0.25f;
+ float ny = (y1 + y1 + y2 + y2) * 0.25f;
+ float nz = (z1 + z2 + z3 + z4) * 0.25f;
+ float nLen = (float) Math.sqrt(nx * nx + ny * ny + nz * nz);
+ if (nLen > 0) {
+ nx /= nLen;
+ ny /= nLen;
+ nz /= nLen;
+ }
+
+ tess.setNormal(nx, ny, nz);
+ tess.addVertex(x1, y1, z1);
+ tess.addVertex(x2, y1, z2);
+ tess.addVertex(x3, y2, z3);
+ tess.addVertex(x4, y2, z4);
+ }
+ }
+
+ tess.draw();
+ }
+
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java
new file mode 100644
index 000000000..bb1f94cab
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyExplosion.java
@@ -0,0 +1,211 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.entity.EntityEnergyExplosion;
+import net.minecraft.entity.Entity;
+import noppes.npcs.config.ConfigClient;
+import org.lwjgl.opengl.GL11;
+
+/**
+ * Voxel-style renderer for {@link EntityEnergyExplosion}.
+ * Draws expanding cubic shells with a short fade-out.
+ * Uses batched cube rendering for performance — all cubes of each layer
+ * are drawn in a single tessellator pass instead of per-cube draw calls.
+ */
+@SideOnly(Side.CLIENT)
+public class RenderEnergyExplosion extends RenderEnergy {
+
+ private static final float MAX_OUTER_ALPHA = 0.85f;
+ private static final float MAX_INNER_ALPHA = 1.0f;
+ private static final float MAX_SMOKE_CUBE_ALPHA = 0.55f;
+
+ @Override
+ public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ if (shouldSkipInitialActiveRender(entity)) return;
+ if (!(entity instanceof EntityEnergyExplosion)) return;
+ if (ConfigClient.LowResExplosion) return;
+ EntityEnergyExplosion explosion = (EntityEnergyExplosion) entity;
+
+ setupRenderState();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ float radius = explosion.getInterpolatedRadius(partialTicks);
+ float life = explosion.getLifeProgress(partialTicks);
+ if (radius > 0.01f && life < 1.0f) {
+ renderVoxelBurst(explosion, radius, life);
+ if (explosion.hasLightningEffect()) {
+ renderAttachedLightning(explosion, 0.55f, Math.max(0.7f, radius * 0.45f));
+ }
+ }
+
+ GL11.glPopMatrix();
+ restoreRenderState();
+ }
+
+ private void renderVoxelBurst(EntityEnergyExplosion explosion, float radius, float life) {
+ int outerColor = explosion.getOuterColor();
+ int innerColor = explosion.getInnerColor();
+ boolean hasOuter = explosion.isOuterColorEnabled();
+
+ float fade = 1.0f - life;
+ float outerAlpha = Math.min(MAX_OUTER_ALPHA, (0.25f + fade * 0.75f) * explosion.getOuterColorAlpha());
+ float innerAlpha = Math.min(MAX_INNER_ALPHA, (0.30f + fade * 0.80f) * explosion.getInnerAlpha());
+
+ int steps = Math.max(2, Math.min(6, (int) Math.ceil(radius * 0.65f) + 1));
+ float cell = radius / steps;
+ float cubeHalf = Math.max(0.04f, cell * 0.22f * (0.90f - life * 0.25f));
+ float outerScale = hasOuter ? 1.0f + explosion.getOuterColorWidth() * 0.35f : 1.0f;
+ long seed = explosion.getRenderSeed();
+
+ // Pre-extract RGB for batched rendering
+ float outerR = ((outerColor >> 16) & 0xFF) / 255.0f;
+ float outerG = ((outerColor >> 8) & 0xFF) / 255.0f;
+ float outerB = (outerColor & 0xFF) / 255.0f;
+ float innerR = ((innerColor >> 16) & 0xFF) / 255.0f;
+ float innerG = ((innerColor >> 8) & 0xFF) / 255.0f;
+ float innerB = (innerColor & 0xFF) / 255.0f;
+
+ GL11.glDepthMask(false);
+
+ // Smoke layer — single batched pass
+ renderSmokeVoxelShell(radius, life, seed);
+
+ // Outer color layer — single batched pass
+ if (hasOuter) {
+ float outerHalf = cubeHalf * outerScale;
+ float oa = outerAlpha * fade;
+ beginCubeBatch();
+ for (int ix = -steps; ix <= steps; ix++) {
+ for (int iy = -steps; iy <= steps; iy++) {
+ for (int iz = -steps; iz <= steps; iz++) {
+ int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
+ if (edge != steps) continue;
+ if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue;
+
+ float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f;
+ float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f;
+ float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f;
+ addBatchedCube(px, py, pz, outerHalf, outerR, outerG, outerB, oa);
+ }
+ }
+ }
+ endCubeBatch();
+ }
+
+ // Inner color layer — single batched pass
+ {
+ float innerHalf = cubeHalf * 0.9f;
+ float ia = innerAlpha * fade;
+ beginCubeBatch();
+ for (int ix = -steps; ix <= steps; ix++) {
+ for (int iy = -steps; iy <= steps; iy++) {
+ for (int iz = -steps; iz <= steps; iz++) {
+ int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
+ if (edge != steps) continue;
+ if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue;
+
+ float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f;
+ float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f;
+ float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f;
+ addBatchedCube(px, py, pz, innerHalf, innerR, innerG, innerB, ia);
+ }
+ }
+ }
+ endCubeBatch();
+ }
+
+ renderCoreFlash(innerColor, innerAlpha, radius, cubeHalf, life);
+ GL11.glDepthMask(true);
+ }
+
+ /**
+ * Adds large translucent white/gray cubes to fake a smoky volumetric expansion.
+ * All smoke cubes are batched into a single draw call.
+ */
+ private void renderSmokeVoxelShell(float radius, float life, long seed) {
+ int smokeSteps = Math.max(2, Math.min(5, (int) Math.ceil(radius * 0.5f) + 1));
+ float smokeCell = radius / smokeSteps * 1.2f;
+ float smokeJitter = smokeCell * 0.28f;
+ float smokeCubeHalf = Math.max(0.07f, smokeCell * 0.24f * (0.95f - life * 0.25f));
+ float smokeAlpha = Math.min(MAX_SMOKE_CUBE_ALPHA, (0.15f + (1.0f - life) * 0.55f));
+
+ // White = 1,1,1 Gray (0xDCDCDC) = 0.863,0.863,0.863
+ beginCubeBatch();
+ for (int ix = -smokeSteps; ix <= smokeSteps; ix++) {
+ for (int iy = -smokeSteps; iy <= smokeSteps; iy++) {
+ for (int iz = -smokeSteps; iz <= smokeSteps; iz++) {
+ int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
+ if (edge < smokeSteps - 1) continue;
+
+ int h = hash(ix * 5, iy * 7, iz * 11, seed ^ 0x4f1bbcdcL);
+ if ((h & 3) != 0) continue;
+ if (life > 0.72f && ((h >>> 5) & 7) > 2) continue;
+
+ float px = ix * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 1) * smokeJitter;
+ float py = iy * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 2) * smokeJitter;
+ float pz = iz * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 3) * smokeJitter;
+
+ boolean isWhite = ((h >>> 9) & 1) == 0;
+ float gray = isWhite ? 1.0f : 0.863f;
+ float alpha = smokeAlpha * (0.78f + (((h >>> 10) & 15) / 15.0f) * 0.22f);
+ addBatchedCube(px, py, pz, smokeCubeHalf, gray, gray, gray, alpha);
+ }
+ }
+ }
+ endCubeBatch();
+ }
+
+ /**
+ * White-hot core flash pass for the initial frames.
+ */
+ private void renderCoreFlash(int innerColor, float innerAlpha, float radius, float cubeHalf, float life) {
+ float flash = saturate((0.60f - life) / 0.60f);
+ if (flash <= 0.0f) return;
+
+ float coreHalf = Math.max(cubeHalf, radius * 0.07f) * (1.0f + flash * 0.55f);
+ float whiteAlpha = Math.min(1.0f, 0.25f + flash * 0.95f);
+ float innerFlashAlpha = Math.min(1.0f, innerAlpha * (0.45f + flash * 0.95f));
+
+ renderCube(0xFFFFFF, whiteAlpha, coreHalf * 1.45f);
+ renderCube(innerColor, innerFlashAlpha, coreHalf * 0.82f);
+ }
+
+ private float saturate(float value) {
+ if (value < 0.0f) return 0.0f;
+ if (value > 1.0f) return 1.0f;
+ return value;
+ }
+
+ private boolean shouldRenderVoxel(int ix, int iy, int iz, int steps, long seed, float life) {
+ int h = hash(ix, iy, iz, seed);
+
+ int keepMask = steps >= 5 ? 3 : 1;
+ if ((h & keepMask) != 0) return false;
+
+ if (life > 0.55f) {
+ int decay = (h >>> 3) & 7;
+ if (decay > 2) return false;
+ }
+
+ return true;
+ }
+
+ private float jitter(int ix, int iy, int iz, long seed, int channel) {
+ int h = hash(ix + channel * 17, iy - channel * 31, iz + channel * 47, seed);
+ return (((h >>> 8) & 1023) / 1023.0f) - 0.5f;
+ }
+
+ private int hash(int x, int y, int z, long seed) {
+ long h = seed;
+ h ^= (long) x * 73428767L;
+ h ^= (long) y * 912931L;
+ h ^= (long) z * 19349663L;
+ h ^= (h >>> 33);
+ h *= 0xff51afd7ed558ccdL;
+ h ^= (h >>> 33);
+ return (int) h;
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java
similarity index 72%
rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java
rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java
index e70e5c6ba..8b0c79b65 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityLaser.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java
@@ -3,19 +3,23 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
-import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityLaser;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* Renders the AbilityLaser entity as a rectangular beam with clear inner/outer colors.
- *
+ *
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
-public class RenderAbilityLaser extends RenderAbilityProjectile {
+public class RenderEnergyLaser extends RenderEnergy {
+
+ private final Map tipLightningStates = new HashMap<>();
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
@@ -23,21 +27,24 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
setupRenderState();
+ // Proximity alpha fade for owner (lasers are always attached, never age out)
+ float proximityAlpha = getProximityAlphaFactor(laser, x, y, z, true);
+
if (laser.isCharging()) {
- renderChargingOrb(laser, x, y, z, partialTicks);
+ renderChargingOrb(laser, x, y, z, partialTicks, proximityAlpha);
restoreRenderState();
return;
}
- // Get laser parameters
- double startX = laser.getStartX();
- double startY = laser.getStartY();
- double startZ = laser.getStartZ();
- double endX = laser.getEndX();
- double endY = laser.getEndY();
- double endZ = laser.getEndZ();
- float width = laser.getLaserWidth();
- float alpha = laser.getLingerAlpha();
+ // Get interpolated laser positions for smooth rendering between ticks
+ double startX = laser.getInterpolatedStartX(partialTicks);
+ double startY = laser.getInterpolatedStartY(partialTicks);
+ double startZ = laser.getInterpolatedStartZ(partialTicks);
+ double endX = laser.getInterpolatedEndX(partialTicks);
+ double endY = laser.getInterpolatedEndY(partialTicks);
+ double endZ = laser.getInterpolatedEndZ(partialTicks);
+ float width = laser.getInterpolatedLaserWidth(partialTicks);
+ float alpha = 1.0f;
// Calculate render offset (entity position is used as reference)
double offsetX = x - laser.posX;
@@ -70,7 +77,9 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Calculate perpendicular vectors (one horizontal, one vertical relative to beam)
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
- upX = 1; upY = 0; upZ = 0;
+ upX = 1;
+ upY = 0;
+ upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -89,6 +98,25 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
double vertY = dz * horzX - dx * horzZ;
double vertZ = dx * horzY - dy * horzX;
+ // Rotate perpendicular vectors around beam axis (Rodrigues' rotation)
+ float rotationSpeed = laser.getRotationSpeed();
+ if (rotationSpeed != 0.0f) {
+ double angle = (laser.ticksExisted + partialTicks) * rotationSpeed * Math.PI / 180.0;
+ double cosA = Math.cos(angle);
+ double sinA = Math.sin(angle);
+
+ double rHorzX = horzX * cosA + vertX * sinA;
+ double rHorzY = horzY * cosA + vertY * sinA;
+ double rHorzZ = horzZ * cosA + vertZ * sinA;
+
+ double rVertX = -horzX * sinA + vertX * cosA;
+ double rVertY = -horzY * sinA + vertY * cosA;
+ double rVertZ = -horzZ * sinA + vertZ * cosA;
+
+ horzX = rHorzX; horzY = rHorzY; horzZ = rHorzZ;
+ vertX = rVertX; vertY = rVertY; vertZ = rVertZ;
+ }
+
// Inner scale defines the core width
float innerScale = 0.6f;
float innerWidth = width * innerScale;
@@ -99,36 +127,36 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
float outerWidth = innerWidth + laser.getOuterColorWidth() * width;
GL11.glDepthMask(false);
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
- renderEndX, renderEndY, renderEndZ,
- horzX, horzY, horzZ, vertX, vertY, vertZ,
- outerWidth, laser.getOuterColor(), alpha * 0.4f);
+ renderEndX, renderEndY, renderEndZ,
+ horzX, horzY, horzZ, vertX, vertY, vertZ,
+ outerWidth, laser.getOuterColor(), alpha * 0.4f * proximityAlpha);
// Render middle layer (halfway between inner and outer)
float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f;
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
- renderEndX, renderEndY, renderEndZ,
- horzX, horzY, horzZ, vertX, vertY, vertZ,
- midWidth, laser.getOuterColor(), alpha * 0.7f);
+ renderEndX, renderEndY, renderEndZ,
+ horzX, horzY, horzZ, vertX, vertY, vertZ,
+ midWidth, laser.getOuterColor(), alpha * 0.7f * proximityAlpha);
GL11.glDepthMask(true);
}
// Render inner core (solid)
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
- renderEndX, renderEndY, renderEndZ,
- horzX, horzY, horzZ, vertX, vertY, vertZ,
- innerWidth, laser.getInnerColor(), alpha);
+ renderEndX, renderEndY, renderEndZ,
+ horzX, horzY, horzZ, vertX, vertY, vertZ,
+ innerWidth, laser.getInnerColor(), alpha * laser.getInnerAlpha() * proximityAlpha);
// Render lightning along the laser beam
if (laser.hasLightningEffect() && laser.getCurrentLength() > 0.1f) {
renderLaserLightning(laser, renderStartX, renderStartY, renderStartZ,
- renderEndX, renderEndY, renderEndZ, width);
+ renderEndX, renderEndY, renderEndZ, width);
}
restoreRenderState();
}
- private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks) {
- float headSize = laser.getLaserWidth() * 1.5f;
+ private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) {
+ float headSize = laser.getInterpolatedLaserWidth(partialTicks) * 0.5f;
float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks);
float size = headSize * chargeProgress;
@@ -147,7 +175,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render lightning during charging if enabled
if (laser.hasLightningEffect()) {
- renderAttachedLightning(laser, scale);
+ renderAttachedLightning(laser, 0.6f * 0.5f, scale);
}
GL11.glPushMatrix();
@@ -159,7 +187,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render outer glow only if enabled
if (laser.isOuterColorEnabled()) {
float outerScale = innerScale + laser.getOuterColorWidth();
- float outerAlpha = laser.getOuterColorAlpha();
+ float outerAlpha = laser.getOuterColorAlpha() * proximityAlpha;
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
@@ -170,7 +198,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
- renderCube(innerColor, 1.0f, 0.5f);
+ renderCube(innerColor, laser.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -180,8 +208,8 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
* Render lightning effects along the laser beam at multiple points.
*/
private void renderLaserLightning(EntityAbilityLaser laser,
- double startX, double startY, double startZ,
- double endX, double endY, double endZ, float width) {
+ double startX, double startY, double startZ,
+ double endX, double endY, double endZ, float width) {
AttachedLightningRenderer.LightningState state = getLightningState(laser);
float density = laser.getLightningDensity();
@@ -215,50 +243,28 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
}
- private void renderAttachedLightning(EntityAbilityLaser laser, float headScale) {
- AttachedLightningRenderer.LightningState state = getLightningState(laser);
-
- float density = laser.getLightningDensity();
- // Lightning radius extends outward from inner surface (innerScale = 0.6)
- float innerRadius = 0.6f * headScale * 0.5f;
- float radius = innerRadius + laser.getLightningRadius() * headScale;
- int outerColor = laser.getOuterColor();
- int innerColor = laser.getInnerColor();
- int fadeTime = laser.getLightningFadeTime();
-
- state.update(density, radius, outerColor, innerColor, fadeTime);
- state.render();
- }
-
- /**
- * Get or create the main lightning state for the laser.
- */
- private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityLaser laser) {
- if (laser.lightningState == null) {
- laser.lightningState = new AttachedLightningRenderer.LightningState();
- }
- return (AttachedLightningRenderer.LightningState) laser.lightningState;
- }
-
/**
* Get or create the tip lightning state for the laser.
- * Stored as a secondary object in lightningState2.
+ * Persisted per entity ID so arcs accumulate and fade properly across frames.
*/
private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) {
- // Use a simple approach - store in a transient field
- // Since lightningState is already used, we'll create a new state each time
- // This works because we're updating and rendering immediately
- return new AttachedLightningRenderer.LightningState();
+ int id = laser.getEntityId();
+ AttachedLightningRenderer.LightningState state = tipLightningStates.get(id);
+ if (state == null) {
+ state = new AttachedLightningRenderer.LightningState();
+ tipLightningStates.put(id, state);
+ }
+ return state;
}
/**
* Render a beam as a 3D rectangular prism (box along a line).
*/
private void renderBeamRectangle(double x1, double y1, double z1,
- double x2, double y2, double z2,
- double horzX, double horzY, double horzZ,
- double vertX, double vertY, double vertZ,
- float width, int color, float alpha) {
+ double x2, double y2, double z2,
+ double horzX, double horzY, double horzZ,
+ double vertX, double vertY, double vertZ,
+ float width, int color, float alpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java
similarity index 58%
rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java
rename to src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java
index 048b3642f..5efe83222 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilityOrb.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java
@@ -2,9 +2,10 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
-import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityOrb;
import net.minecraft.entity.Entity;
+import net.minecraft.util.Vec3;
+import noppes.npcs.util.MathUtil;
import org.lwjgl.opengl.GL11;
/**
@@ -12,7 +13,7 @@ import org.lwjgl.opengl.GL11;
* Minecraft-style blocky appearance using Tessellator.
*/
@SideOnly(Side.CLIENT)
-public class RenderAbilityOrb extends RenderAbilityProjectile {
+public class RenderEnergyOrb extends RenderEnergy {
private static final int LIGHTNING_FADE_TICKS = 6;
@@ -20,6 +21,10 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilityOrb orb = (EntityAbilityOrb) entity;
+ if (shouldSkipInitialActiveRender(entity)) {
+ return;
+ }
+
setupRenderState();
GL11.glPushMatrix();
@@ -35,7 +40,22 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions
if (orb.hasLightningEffect()) {
- renderAttachedLightning(orb, scale);
+ renderAttachedLightning(orb, 0.6f * 0.5f, scale);
+ }
+
+ double motionX = entity.motionX;
+ double motionY = entity.motionY;
+ double motionZ = entity.motionZ;
+ double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
+
+ // Only apply motion-based facing when speed is meaningful.
+ // Near-zero motion makes atan2 unstable, producing jittery angles.
+ if (speedSq > 0.0001) {
+ Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
+ float motionYaw = MathUtil.getYaw(motionVec);
+ float motionPitch = MathUtil.getPitch(motionVec);
+ GL11.glRotatef(motionYaw, 0, 1, 0);
+ GL11.glRotatef(motionPitch, 1, 0, 0);
}
// Use entity's interpolated rotation for smooth spinning
@@ -49,6 +69,9 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
// Inner scale defines the core size
float innerScale = 0.6f;
+ // Proximity alpha fade for owner
+ float proximityAlpha = getProximityAlphaFactor(orb, x, y, z);
+
// Render outer cube (translucent) - only if enabled
// outerColorWidth is an additive offset from inner size
if (orb.isOuterColorEnabled()) {
@@ -56,14 +79,14 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
- renderCube(orb.getOuterColor(), orb.getOuterColorAlpha(), 0.5f);
+ renderCube(orb.getOuterColor(), orb.getOuterColorAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glDepthMask(true);
}
// Render inner cube (solid)
GL11.glScalef(innerScale, innerScale, innerScale);
- renderCube(orb.getInnerColor(), 1.0f, 0.5f);
+ renderCube(orb.getInnerColor(), orb.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -71,36 +94,4 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
restoreRenderState();
}
- /**
- * Render fading lightning arcs attached to the orb (in local space).
- * Arcs persist for a few ticks and fade out, while staying attached to the orb.
- */
- private void renderAttachedLightning(EntityAbilityOrb orb, float orbScale) {
- // Get or create the lightning state for this entity
- AttachedLightningRenderer.LightningState state = getLightningState(orb);
-
- float density = orb.getLightningDensity();
- // Lightning radius extends outward from inner surface (innerScale = 0.6)
- float innerRadius = 0.6f * orbScale * 0.5f; // Half size of inner cube
- float radius = innerRadius + orb.getLightningRadius() * orbScale;
- int outerColor = orb.getOuterColor();
- int innerColor = orb.getInnerColor();
- int fadeTime = orb.getLightningFadeTime();
-
- // Update: age existing arcs, spawn new ones based on density
- state.update(density, radius, outerColor, innerColor, fadeTime);
-
- // Render all active arcs in local space (they move with the orb)
- state.render();
- }
-
- /**
- * Get or create the lightning state for an entity.
- */
- private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityOrb orb) {
- if (orb.lightningState == null) {
- orb.lightningState = new AttachedLightningRenderer.LightningState();
- }
- return (AttachedLightningRenderer.LightningState) orb.lightningState;
- }
}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java
new file mode 100644
index 000000000..5cb9a7abc
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyPanel.java
@@ -0,0 +1,143 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.entity.EntityEnergyPanel;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.entity.Entity;
+import org.lwjgl.opengl.GL11;
+
+/**
+ * Renders the Energy Panel entity as a flat translucent rectangle.
+ * Used by both Energy Wall and Energy Shield abilities.
+ * Voxel-blocky style with inner/outer layers.
+ */
+@SideOnly(Side.CLIENT)
+public class RenderEnergyPanel extends RenderEnergyBarrier {
+
+ @Override
+ public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ if (shouldSkipInitialActiveRender(entity)) {
+ return;
+ }
+ EntityEnergyPanel panel = (EntityEnergyPanel) entity;
+
+ float width = panel.getPanelData().panelWidth;
+ float height = panel.getPanelData().panelHeight;
+ float healthPercent = panel.getHealthPercent();
+
+ // Interpolate panel yaw for smooth rotation between ticks
+ float prevYaw = panel.getPrevPanelYaw();
+ float currentYaw = panel.getPanelYaw();
+ float yawDelta = currentYaw - prevYaw;
+ // Wrap angle delta to -180..180 for shortest rotation path
+ while (yawDelta > 180.0f) yawDelta -= 360.0f;
+ while (yawDelta < -180.0f) yawDelta += 360.0f;
+ float renderYaw = prevYaw + yawDelta * partialTicks;
+
+ setupRenderState();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Lightning BEFORE rotation for uniform spread (like Orb pattern)
+ if (panel.hasLightningEffect()) {
+ renderAttachedLightning(panel, 0.9f, Math.max(width, height) * 0.5f);
+ }
+
+ // Rotate panel to face the correct direction (interpolated)
+ GL11.glRotatef(-renderYaw, 0.0f, 1.0f, 0.0f);
+
+ // Hit flash
+ float flashAlpha = computeFlashAlpha(panel);
+
+ // Subtle pulsing
+ float pulseTime = entity.ticksExisted + partialTicks;
+ float pulse = (float) Math.sin(pulseTime * 0.08f) * 0.02f;
+ float scale = 1.0f + pulse;
+
+ GL11.glPushMatrix();
+ GL11.glScalef(scale, scale, scale);
+
+ float innerScale = 1.0f;
+ float panelThickness = 0.1f;
+
+ // Render outer panel (translucent glow)
+ if (panel.isOuterColorEnabled()) {
+ float outerScale = 1.0f + panel.getOuterColorWidth() * 0.15f;
+ float outerAlpha = panel.getOuterColorAlpha() * healthPercent;
+ GL11.glDepthMask(false);
+ renderPanel(panel.getOuterColor(), outerAlpha + (panel.getOuterColorAlpha() > 0 ? flashAlpha : 0),
+ width * 0.5f * outerScale, height * 0.5f * outerScale, panelThickness * 1.5f);
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner panel (uses configurable innerAlpha for semi-transparency)
+ renderPanel(panel.getInnerColor(), panel.getInnerAlpha(),
+ width * 0.5f * innerScale, height * 0.5f * innerScale, panelThickness);
+
+ GL11.glPopMatrix();
+ GL11.glPopMatrix();
+
+ restoreRenderState();
+ }
+
+ /**
+ * Render a flat panel (thin box) centered at origin.
+ * Panel faces along the Z axis (width on X, height on Y).
+ * All 6 faces batched into a single draw call.
+ */
+ private void renderPanel(int color, float alpha, float halfWidth, float halfHeight, float halfThickness) {
+ float[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+
+ // Front face (z+)
+ tess.setNormal(0, 0, 1);
+ tess.addVertex(-halfWidth, -halfHeight, halfThickness);
+ tess.addVertex(halfWidth, -halfHeight, halfThickness);
+ tess.addVertex(halfWidth, halfHeight, halfThickness);
+ tess.addVertex(-halfWidth, halfHeight, halfThickness);
+
+ // Back face (z-)
+ tess.setNormal(0, 0, -1);
+ tess.addVertex(halfWidth, -halfHeight, -halfThickness);
+ tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
+ tess.addVertex(-halfWidth, halfHeight, -halfThickness);
+ tess.addVertex(halfWidth, halfHeight, -halfThickness);
+
+ // Top edge (y+)
+ tess.setNormal(0, 1, 0);
+ tess.addVertex(-halfWidth, halfHeight, halfThickness);
+ tess.addVertex(halfWidth, halfHeight, halfThickness);
+ tess.addVertex(halfWidth, halfHeight, -halfThickness);
+ tess.addVertex(-halfWidth, halfHeight, -halfThickness);
+
+ // Bottom edge (y-)
+ tess.setNormal(0, -1, 0);
+ tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
+ tess.addVertex(halfWidth, -halfHeight, -halfThickness);
+ tess.addVertex(halfWidth, -halfHeight, halfThickness);
+ tess.addVertex(-halfWidth, -halfHeight, halfThickness);
+
+ // Right edge (x+)
+ tess.setNormal(1, 0, 0);
+ tess.addVertex(halfWidth, -halfHeight, halfThickness);
+ tess.addVertex(halfWidth, -halfHeight, -halfThickness);
+ tess.addVertex(halfWidth, halfHeight, -halfThickness);
+ tess.addVertex(halfWidth, halfHeight, halfThickness);
+
+ // Left edge (x-)
+ tess.setNormal(-1, 0, 0);
+ tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
+ tess.addVertex(-halfWidth, -halfHeight, halfThickness);
+ tess.addVertex(-halfWidth, halfHeight, halfThickness);
+ tess.addVertex(-halfWidth, halfHeight, -halfThickness);
+
+ tess.draw();
+ }
+
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java
new file mode 100644
index 000000000..589818905
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergySlicer.java
@@ -0,0 +1,131 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.entity.EntityEnergySlicer;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.entity.Entity;
+import org.lwjgl.opengl.GL11;
+
+/**
+ * Renders the Energy Slicer entity as a thin wide blade.
+ * Oriented perpendicular to travel direction.
+ * Inner solid core with outer translucent glow.
+ */
+@SideOnly(Side.CLIENT)
+public class RenderEnergySlicer extends RenderEnergy {
+
+ @Override
+ public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ if (shouldSkipInitialActiveRender(entity)) {
+ return;
+ }
+ EntityEnergySlicer slicer = (EntityEnergySlicer) entity;
+
+ float width = slicer.getSliceWidth();
+ float thickness = slicer.getSliceThickness();
+
+ // During charging, width/thickness grow from 0.01 to target via updateCharging().
+ // Use current dimensions directly - no separate sizeRatio needed.
+ if (width <= 0.01f) return;
+
+ setupRenderState();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Lightning BEFORE rotation for uniform spread (like Orb pattern)
+ if (slicer.hasLightningEffect()) {
+ renderAttachedLightning(slicer, 0.7f, width * 0.5f);
+ }
+
+ // Orient perpendicular to travel direction
+ float travelYaw = slicer.getTravelYaw();
+ float travelPitch = slicer.getTravelPitch();
+ GL11.glRotatef(travelYaw, 0.0f, 1.0f, 0.0f);
+ GL11.glRotatef(travelPitch, 1.0f, 0.0f, 0.0f);
+
+ float innerScale = 0.7f;
+
+ // Proximity alpha fade for owner
+ float proximityAlpha = getProximityAlphaFactor(slicer, x, y, z);
+
+ // Render outer blade (translucent glow)
+ if (slicer.isOuterColorEnabled()) {
+ float outerScale = 1.0f + slicer.getOuterColorWidth() * 0.2f;
+ GL11.glDepthMask(false);
+ renderBlade(slicer.getOuterColor(), slicer.getOuterColorAlpha() * proximityAlpha,
+ width * 0.5f * outerScale, thickness * 2.0f, 0.05f);
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner blade (solid core)
+ renderBlade(slicer.getInnerColor(), slicer.getInnerAlpha() * proximityAlpha,
+ width * 0.5f * innerScale, thickness, 0.03f);
+
+ GL11.glPopMatrix();
+
+ restoreRenderState();
+ }
+
+ /**
+ * Render a thin wide blade shape.
+ * The blade extends along X (width), thin on Y (thickness), and very thin on Z (depth).
+ * All 6 faces batched into a single draw call.
+ */
+ private void renderBlade(int color, float alpha, float halfWidth, float halfHeight, float halfDepth) {
+ float[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+
+ // Front face (z+)
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(0, 0, 1);
+ tess.addVertex(-halfWidth, -halfHeight, halfDepth);
+ tess.addVertex(halfWidth, -halfHeight, halfDepth);
+ tess.addVertex(halfWidth, halfHeight, halfDepth);
+ tess.addVertex(-halfWidth, halfHeight, halfDepth);
+
+ // Back face (z-)
+ tess.setNormal(0, 0, -1);
+ tess.addVertex(halfWidth, -halfHeight, -halfDepth);
+ tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
+ tess.addVertex(-halfWidth, halfHeight, -halfDepth);
+ tess.addVertex(halfWidth, halfHeight, -halfDepth);
+
+ // Top edge (y+)
+ tess.setColorRGBA_F(r, g, b, alpha * 0.8f);
+ tess.setNormal(0, 1, 0);
+ tess.addVertex(-halfWidth, halfHeight, halfDepth);
+ tess.addVertex(halfWidth, halfHeight, halfDepth);
+ tess.addVertex(halfWidth, halfHeight, -halfDepth);
+ tess.addVertex(-halfWidth, halfHeight, -halfDepth);
+
+ // Bottom edge (y-)
+ tess.setNormal(0, -1, 0);
+ tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
+ tess.addVertex(halfWidth, -halfHeight, -halfDepth);
+ tess.addVertex(halfWidth, -halfHeight, halfDepth);
+ tess.addVertex(-halfWidth, -halfHeight, halfDepth);
+
+ // Right edge (x+)
+ tess.setColorRGBA_F(r, g, b, alpha * 0.6f);
+ tess.setNormal(1, 0, 0);
+ tess.addVertex(halfWidth, -halfHeight, halfDepth);
+ tess.addVertex(halfWidth, -halfHeight, -halfDepth);
+ tess.addVertex(halfWidth, halfHeight, -halfDepth);
+ tess.addVertex(halfWidth, halfHeight, halfDepth);
+
+ // Left edge (x-)
+ tess.setNormal(-1, 0, 0);
+ tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
+ tess.addVertex(-halfWidth, -halfHeight, halfDepth);
+ tess.addVertex(-halfWidth, halfHeight, halfDepth);
+ tess.addVertex(-halfWidth, halfHeight, -halfDepth);
+
+ tess.draw();
+ }
+
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java
similarity index 59%
rename from src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java
rename to src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java
index 10705d762..01ec9b429 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/RenderAbilitySweeper.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java
@@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
-import kamkeel.npcs.entity.EntityAbilitySweeper;
+import kamkeel.npcs.entity.EntityEnergySweeper;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
@@ -15,16 +15,17 @@ import org.lwjgl.opengl.GL11;
* Uses similar rendering style to the Beam trail for visual consistency.
*/
@SideOnly(Side.CLIENT)
-public class RenderAbilitySweeper extends Render {
+public class RenderSweeper extends Render {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
- EntityAbilitySweeper sweeper = (EntityAbilitySweeper) entity;
+ EntityEnergySweeper sweeper = (EntityEnergySweeper) entity;
setupRenderState();
float beamLength = sweeper.getBeamLength();
float beamWidth = sweeper.getBeamWidth();
+ float beamHeight = sweeper.getBeamHeight();
int innerColor = sweeper.getInnerColor();
int outerColor = sweeper.getOuterColor();
boolean outerColorEnabled = sweeper.isOuterColorEnabled();
@@ -38,7 +39,7 @@ public class RenderAbilitySweeper extends Render {
GL11.glRotatef(-angle, 0, 1, 0); // Negative for correct direction
// Render the beam extending in the +Z direction (like beam trail segments)
- renderBeam(beamLength, beamWidth, innerColor, outerColor, outerColorEnabled, outerColorWidth);
+ renderBeam(beamLength, beamWidth, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth);
GL11.glPopMatrix();
@@ -70,8 +71,10 @@ public class RenderAbilitySweeper extends Render {
/**
* Render beam using the same style as the Beam entity trail.
* Three layers: outer glow, middle, inner core.
+ * outerColorWidth is an additive offset from inner width (consistent with other renderers).
+ * Width and height control the rectangular cross-section independently.
*/
- private void renderBeam(float length, float width, int innerColor, int outerColor,
+ private void renderBeam(float length, float width, float height, int innerColor, int outerColor,
boolean outerColorEnabled, float outerColorWidth) {
// Extract colors
float outerR = ((outerColor >> 16) & 0xFF) / 255.0f;
@@ -82,30 +85,40 @@ public class RenderAbilitySweeper extends Render {
float innerG = ((innerColor >> 8) & 0xFF) / 255.0f;
float innerB = (innerColor & 0xFF) / 255.0f;
+ // Inner scale defines the core size (consistent with other renderers)
+ float innerScale = 0.6f;
+ float innerWidth = width * innerScale;
+ float innerHeight = height * innerScale;
+
// Render from origin (0,0,0) to (0,0,length) in local coords
// After rotation this extends in the correct world direction
- // Outer glow (wider, translucent) - like beam trail - only if enabled
+ // Outer glow (wider, translucent) - only if enabled
+ // outerColorWidth is additive offset from inner size
if (outerColorEnabled) {
+ float outerWidth = innerWidth + outerColorWidth * width;
+ float outerHeight = innerHeight + outerColorWidth * height;
GL11.glDepthMask(false);
- renderBeamSegment(0, 0, 0, 0, 0, length, width * outerColorWidth, outerR, outerG, outerB, 0.3f);
+ renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f);
GL11.glDepthMask(true);
- // Middle layer
- renderBeamSegment(0, 0, 0, 0, 0, length, width * 1.3f, outerR, outerG, outerB, 0.6f);
+ // Middle layer (halfway between inner and outer)
+ float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f;
+ float midHeight = innerHeight + (outerHeight - innerHeight) * 0.5f;
+ renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, midHeight, outerR, outerG, outerB, 0.6f);
}
- // Inner core (solid) - like beam trail inner
- renderBeamSegment(0, 0, 0, 0, 0, length, width * 0.6f, innerR, innerG, innerB, 1.0f);
+ // Inner core (solid)
+ renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f);
}
/**
- * Render a beam segment as a 3D rectangular prism.
- * Uses the same approach as RenderAbilityBeam.renderBeamRectangle.
+ * Render a beam segment as a 3D rectangular prism with independent width and height.
+ * Uses the same approach as RenderEnergyBeam.renderBeamRectangle.
*/
private void renderBeamSegment(double x1, double y1, double z1,
- double x2, double y2, double z2,
- float width, float r, float g, float b, float a) {
+ double x2, double y2, double z2,
+ float width, float height, float r, float g, float b, float a) {
// Calculate direction
double dx = x2 - x1;
double dy = y2 - y1;
@@ -121,7 +134,9 @@ public class RenderAbilitySweeper extends Render {
// Calculate perpendicular vectors
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
- upX = 1; upY = 0; upZ = 0;
+ upX = 1;
+ upY = 0;
+ upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -141,39 +156,40 @@ public class RenderAbilitySweeper extends Render {
double vertZ = dx * horzY - dy * horzX;
float halfWidth = width * 0.5f;
+ float halfHeight = height * 0.5f;
- // Calculate 8 corners of the box
- double s1x = x1 - horzX * halfWidth - vertX * halfWidth;
- double s1y = y1 - horzY * halfWidth - vertY * halfWidth;
- double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth;
+ // Calculate 8 corners of the box (horz scaled by halfWidth, vert scaled by halfHeight)
+ double s1x = x1 - horzX * halfWidth - vertX * halfHeight;
+ double s1y = y1 - horzY * halfWidth - vertY * halfHeight;
+ double s1z = z1 - horzZ * halfWidth - vertZ * halfHeight;
- double s2x = x1 + horzX * halfWidth - vertX * halfWidth;
- double s2y = y1 + horzY * halfWidth - vertY * halfWidth;
- double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth;
+ double s2x = x1 + horzX * halfWidth - vertX * halfHeight;
+ double s2y = y1 + horzY * halfWidth - vertY * halfHeight;
+ double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight;
- double s3x = x1 + horzX * halfWidth + vertX * halfWidth;
- double s3y = y1 + horzY * halfWidth + vertY * halfWidth;
- double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth;
+ double s3x = x1 + horzX * halfWidth + vertX * halfHeight;
+ double s3y = y1 + horzY * halfWidth + vertY * halfHeight;
+ double s3z = z1 + horzZ * halfWidth + vertZ * halfHeight;
- double s4x = x1 - horzX * halfWidth + vertX * halfWidth;
- double s4y = y1 - horzY * halfWidth + vertY * halfWidth;
- double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth;
+ double s4x = x1 - horzX * halfWidth + vertX * halfHeight;
+ double s4y = y1 - horzY * halfWidth + vertY * halfHeight;
+ double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight;
- double e1x = x2 - horzX * halfWidth - vertX * halfWidth;
- double e1y = y2 - horzY * halfWidth - vertY * halfWidth;
- double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth;
+ double e1x = x2 - horzX * halfWidth - vertX * halfHeight;
+ double e1y = y2 - horzY * halfWidth - vertY * halfHeight;
+ double e1z = z2 - horzZ * halfWidth - vertZ * halfHeight;
- double e2x = x2 + horzX * halfWidth - vertX * halfWidth;
- double e2y = y2 + horzY * halfWidth - vertY * halfWidth;
- double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth;
+ double e2x = x2 + horzX * halfWidth - vertX * halfHeight;
+ double e2y = y2 + horzY * halfWidth - vertY * halfHeight;
+ double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight;
- double e3x = x2 + horzX * halfWidth + vertX * halfWidth;
- double e3y = y2 + horzY * halfWidth + vertY * halfWidth;
- double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth;
+ double e3x = x2 + horzX * halfWidth + vertX * halfHeight;
+ double e3y = y2 + horzY * halfWidth + vertY * halfHeight;
+ double e3z = z2 + horzZ * halfWidth + vertZ * halfHeight;
- double e4x = x2 - horzX * halfWidth + vertX * halfWidth;
- double e4y = y2 - horzY * halfWidth + vertY * halfWidth;
- double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth;
+ double e4x = x2 - horzX * halfWidth + vertX * halfHeight;
+ double e4y = y2 - horzY * halfWidth + vertY * halfHeight;
+ double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight;
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java b/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java
new file mode 100644
index 000000000..1d3d92d85
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderZone.java
@@ -0,0 +1,797 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
+import kamkeel.npcs.entity.EntityAbilityZone;
+import kamkeel.npcs.entity.EntityAbilityZone.AccentStyle;
+import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion;
+import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape;
+import kamkeel.npcs.entity.EntityAbilityZone.ZoneType;
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.renderer.OpenGlHelper;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.client.renderer.entity.Render;
+import net.minecraft.entity.Entity;
+import net.minecraft.util.ResourceLocation;
+import noppes.npcs.client.fx.CustomFX;
+import noppes.npcs.client.fx.ZoneParticleFX;
+import org.lwjgl.opengl.GL11;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+
+@SideOnly(Side.CLIENT)
+public class RenderZone extends Render {
+
+ private static final int CIRCLE_SEGMENTS = 32;
+ private static final int ACCENT_LINE_COUNT = 12;
+ private static final Random RANDOM = new Random();
+
+ private final Map lastParticleTick = new HashMap<>();
+ private final Map lightningStates = new HashMap<>();
+
+ private static final int TRIGGER_REVEAL_TICKS = 10;
+
+ private static class Ctx {
+ EntityAbilityZone zone;
+ ZoneShape shape;
+ float radius, height;
+ float ir, ig, ib;
+ float outerR, outerG, outerB;
+ boolean outerEnabled;
+ float time, pulse, rotation, brightness;
+ boolean flash, newTick;
+ float particleDensity, particleScale, animSpeed, lightningDensity;
+ boolean groundFill, rings, border, accents, lightning, particles;
+ float groundAlpha, borderSpeed;
+ int ringCount, accentStyle, particleMotion, particleSize;
+ boolean particleGlow;
+ String particleDir;
+ boolean trapVisible;
+ boolean triggerReveal;
+ float revealFade;
+ }
+
+ @Override
+ public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ EntityAbilityZone zone = (EntityAbilityZone) entity;
+
+ Ctx c = new Ctx();
+ c.zone = zone;
+ c.shape = zone.getShape();
+ c.radius = zone.getRadius();
+ c.height = zone.getZoneHeight();
+
+ int inner = zone.getInnerColor();
+ c.ir = ((inner >> 16) & 0xFF) / 255.0f;
+ c.ig = ((inner >> 8) & 0xFF) / 255.0f;
+ c.ib = (inner & 0xFF) / 255.0f;
+
+ int outer = zone.getOuterColor();
+ c.outerR = ((outer >> 16) & 0xFF) / 255.0f;
+ c.outerG = ((outer >> 8) & 0xFF) / 255.0f;
+ c.outerB = (outer & 0xFF) / 255.0f;
+ c.outerEnabled = zone.isOuterColorEnabled();
+
+ c.particleDensity = zone.getParticleDensity();
+ c.particleScale = zone.getParticleScale();
+ c.animSpeed = zone.getAnimSpeed();
+ c.lightningDensity = zone.getLightningDensity();
+
+ c.groundFill = zone.isGroundFill();
+ c.groundAlpha = zone.getGroundAlpha();
+ c.rings = zone.isRings();
+ c.ringCount = zone.getRingCount();
+ c.border = zone.isBorder();
+ c.borderSpeed = zone.getBorderSpeed();
+ c.accents = zone.isAccents();
+ c.accentStyle = zone.getAccentStyle();
+ c.lightning = zone.isLightning();
+ c.particles = zone.isParticles();
+ c.particleMotion = zone.getParticleMotion();
+ c.particleDir = zone.getParticleDir();
+ c.particleSize = zone.getParticleSize();
+ c.particleGlow = zone.isParticleGlow();
+
+ c.time = zone.ticksExisted + partialTicks;
+ c.pulse = c.time * 0.1f * c.animSpeed;
+ c.rotation = c.time * 1.5f * c.animSpeed;
+
+ c.brightness = 1.0f;
+ c.trapVisible = true;
+ c.triggerReveal = false;
+ c.revealFade = 0.0f;
+
+ if (zone.getZoneType() == ZoneType.TRAP) {
+ c.trapVisible = zone.isVisible();
+
+ // Trigger reveal: 10-tick full visual burst that fades out
+ if (zone.getTriggerFlashTick() >= 0) {
+ float ticksSinceTrigger = zone.ticksExisted - zone.getTriggerFlashTick() + partialTicks;
+ if (ticksSinceTrigger < TRIGGER_REVEAL_TICKS) {
+ c.triggerReveal = true;
+ c.revealFade = Math.max(0.0f, 1.0f - ticksSinceTrigger / TRIGGER_REVEAL_TICKS);
+ }
+ }
+
+ // Skip render entirely if invisible and not in reveal
+ if (!c.trapVisible && !c.triggerReveal) {
+ return;
+ }
+
+ if (!zone.isArmed()) {
+ c.brightness = 0.4f;
+ } else {
+ c.pulse = c.time * 0.2f;
+ }
+ }
+
+ // White flash during first 2 ticks of reveal
+ c.flash = c.triggerReveal && c.revealFade > 0.8f;
+
+ c.newTick = isNewTick(zone);
+
+ setupRenderState();
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+ GL11.glDepthMask(false);
+
+ renderZone(c);
+
+ GL11.glDepthMask(true);
+ GL11.glPopMatrix();
+ restoreRenderState();
+ }
+
+ private boolean isNewTick(EntityAbilityZone zone) {
+ int id = zone.getEntityId();
+ int tick = zone.ticksExisted;
+ Integer last = lastParticleTick.get(id);
+ if (last == null || last != tick) {
+ lastParticleTick.put(id, tick);
+ return true;
+ }
+ return false;
+ }
+
+ private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityZone zone) {
+ int id = zone.getEntityId();
+ AttachedLightningRenderer.LightningState state = lightningStates.get(id);
+ if (state == null) {
+ state = new AttachedLightningRenderer.LightningState();
+ lightningStates.put(id, state);
+ }
+ return state;
+ }
+
+ private void renderZone(Ctx c) {
+ // During trigger reveal, override visual layers for dramatic burst
+ if (c.triggerReveal) {
+ c.brightness = c.revealFade;
+ c.groundFill = true;
+ c.groundAlpha = 0.35f * c.revealFade;
+ c.rings = true;
+ c.ringCount = 3;
+ c.accents = true;
+ c.accentStyle = 2; // FLICKERING
+ c.border = true;
+ }
+
+ float rR = ringR(c), rG = ringG(c), rB = ringB(c);
+
+ if (c.groundFill) {
+ if (c.flash) {
+ renderShapeFill(c.shape, c.radius, 1, 1, 1, 0.5f);
+ } else {
+ renderShapeFill(c.shape, c.radius,
+ c.ir, c.ig, c.ib, c.groundAlpha * c.brightness);
+ }
+ }
+
+ if (c.rings) {
+ int count = Math.max(1, Math.min(5, c.ringCount));
+ for (int i = 0; i < count; i++) {
+ float frac = (i + 1.0f) / (count + 1);
+ float ra = (0.4f + 0.3f * sin(c.pulse + i * Math.PI / 3)) * c.brightness;
+ float yOff = 0.02f + i * 0.01f;
+ renderRingLine(c.shape, c.radius * frac,
+ rR, rG, rB, ra, yOff);
+ }
+ float edgeA = (0.5f + 0.4f * sin(c.pulse + count * Math.PI / 3)) * c.brightness;
+ renderRingLine(c.shape, c.radius, rR, rG, rB, edgeA, 0.02f + count * 0.01f);
+ }
+
+ if (c.border) {
+ renderRotatingBorder(c.shape, c.radius, rR, rG, rB,
+ 0.7f * c.brightness, c.rotation * c.borderSpeed, 0.05f);
+ }
+
+ if (c.accents) {
+ float aa = 0.5f * c.brightness * (0.3f + 0.2f * sin(c.pulse * 0.7f));
+ AccentStyle style = AccentStyle.values()[Math.max(0, Math.min(c.accentStyle, AccentStyle.values().length - 1))];
+ switch (style) {
+ case SWAYING:
+ renderSwayingAccents(c, c.ir, c.ig, c.ib, aa, c.height);
+ break;
+ case FLICKERING:
+ renderFlickeringAccents(c, c.ir, c.ig, c.ib, aa, c.height);
+ break;
+ default:
+ renderVerticalAccents(c.shape, c.radius, c.ir, c.ig, c.ib, aa, c.height, c.rotation * 0.3f);
+ break;
+ }
+ }
+
+ if (c.lightning) {
+ int innerColor = c.zone.getInnerColor();
+ int outerColor = c.outerEnabled ? c.zone.getOuterColor() : innerColor;
+ AttachedLightningRenderer.LightningState state = getLightningState(c.zone);
+ if (c.newTick) {
+ state.tick();
+ float density = 0.4f * c.brightness * c.lightningDensity;
+ if (RANDOM.nextFloat() < density) {
+ double[] p1 = randomPosInZone(c);
+ double[] p2 = randomPosInZone(c);
+ double y1 = RANDOM.nextDouble() * c.height * 0.4;
+ double y2 = RANDOM.nextDouble() * c.height * 0.4;
+ float disp = c.radius * 0.15f;
+ state.addArc(AttachedLightningRenderer.createArcBetween(
+ p1[0], y1, p1[2], p2[0], y2, p2[2], disp, outerColor, innerColor, 6));
+ }
+ if (RANDOM.nextFloat() < density * 0.5f * c.lightningDensity) {
+ double[] edgePos = randomEdgePos(c);
+ double ex = edgePos[0];
+ double ez = edgePos[1];
+ float disp = c.radius * 0.12f;
+ state.addArc(AttachedLightningRenderer.createArcBetween(
+ ex, 0, ez, ex + (RANDOM.nextDouble() - 0.5) * 0.5,
+ c.height * (0.3 + RANDOM.nextDouble() * 0.4),
+ ez + (RANDOM.nextDouble() - 0.5) * 0.5,
+ disp, outerColor, innerColor, 5));
+ }
+ }
+ state.render();
+ GL11.glDepthMask(false);
+ }
+
+ if (c.particles && c.newTick && c.particleDensity > 0) {
+ if (c.particleDir != null && !c.particleDir.isEmpty()) {
+ if (c.particleDir.startsWith("mc:")) {
+ spawnVanillaParticle(c);
+ } else {
+ spawnCustomFXParticle(c);
+ }
+ } else {
+ spawnDefaultParticles(c);
+ }
+ }
+ }
+
+ private void spawnVanillaParticle(Ctx c) {
+ String particleName = c.particleDir.substring(3);
+ int count = Math.round(3 * c.particleDensity);
+ for (int i = 0; i < count; i++) {
+ double[] pos = randomPosInZone(c);
+ double[] motion = getMotionForStyle(c.particleMotion);
+ c.zone.worldObj.spawnParticle(particleName,
+ c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2],
+ motion[0], motion[1], motion[2]);
+ }
+ }
+
+ private void spawnCustomFXParticle(Ctx c) {
+ int count = Math.round(3 * c.particleDensity);
+ for (int i = 0; i < count; i++) {
+ double[] pos = randomPosInZone(c);
+ double[] motion = getMotionForStyle(c.particleMotion);
+ CustomFX fx = new CustomFX(c.zone.worldObj, null, c.particleDir,
+ c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2],
+ 0, 0, 0);
+ fx.motionX = motion[0];
+ fx.motionY = motion[1];
+ fx.motionZ = motion[2];
+ fx.setMaxAge(20 + RANDOM.nextInt(20));
+ fx.width = -1;
+ fx.height = -1;
+ fx.scaleX1 = c.particleScale * 10.0f;
+ fx.scaleY1 = c.particleScale * 10.0f;
+ fx.scaleX2 = fx.scaleX1;
+ fx.scaleY2 = fx.scaleY1;
+ fx.scaleXRate = 0;
+ fx.scaleYRate = 0;
+ fx.HEXColor = c.zone.getInnerColor();
+ fx.facePlayer = true;
+ fx.glows = c.particleGlow;
+ fx.noClip = true;
+ fx.alpha1 = 0.8f;
+ fx.alpha2 = 0.0f;
+ fx.alphaRate = -0.04f;
+ Minecraft.getMinecraft().effectRenderer.addEffect(fx);
+ }
+ }
+
+ private void spawnDefaultParticles(Ctx c) {
+ int count = Math.round(3 * c.particleDensity);
+ ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(c.particleMotion, ParticleMotion.values().length - 1))];
+ for (int i = 0; i < count; i++) {
+ double[] pos = randomPosInZone(c);
+ double mx, my, mz;
+ float gravity;
+ int age;
+ switch (motion) {
+ case DRIFTING:
+ mx = (RANDOM.nextDouble() - 0.5) * 0.005;
+ my = 0.005 + RANDOM.nextDouble() * 0.01;
+ mz = (RANDOM.nextDouble() - 0.5) * 0.005;
+ gravity = 0;
+ age = 40 + RANDOM.nextInt(20);
+ break;
+ case SPARKS:
+ mx = (RANDOM.nextDouble() - 0.5) * 0.08;
+ my = RANDOM.nextDouble() * 0.06;
+ mz = (RANDOM.nextDouble() - 0.5) * 0.08;
+ gravity = 0;
+ age = 4 + RANDOM.nextInt(6);
+ break;
+ default: // RISING
+ mx = (RANDOM.nextDouble() - 0.5) * 0.01;
+ my = 0.01 + RANDOM.nextDouble() * 0.02;
+ mz = (RANDOM.nextDouble() - 0.5) * 0.01;
+ gravity = -0.01f;
+ age = 30 + RANDOM.nextInt(20);
+ break;
+ }
+ float scale = (1.5f + RANDOM.nextFloat() * 1.0f) * c.particleScale;
+ spawnParticle(c.zone, pos[0], pos[1], pos[2], mx, my, mz,
+ c.ir, c.ig, c.ib, 0.7f, scale, age, gravity, c.particleGlow);
+ }
+ }
+
+ private double[] getMotionForStyle(int motionOrdinal) {
+ ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(motionOrdinal, ParticleMotion.values().length - 1))];
+ switch (motion) {
+ case DRIFTING:
+ return new double[]{
+ (RANDOM.nextDouble() - 0.5) * 0.005,
+ 0.005 + RANDOM.nextDouble() * 0.01,
+ (RANDOM.nextDouble() - 0.5) * 0.005
+ };
+ case SPARKS:
+ return new double[]{
+ (RANDOM.nextDouble() - 0.5) * 0.08,
+ RANDOM.nextDouble() * 0.06,
+ (RANDOM.nextDouble() - 0.5) * 0.08
+ };
+ default: // RISING
+ return new double[]{
+ (RANDOM.nextDouble() - 0.5) * 0.01,
+ 0.01 + RANDOM.nextDouble() * 0.02,
+ (RANDOM.nextDouble() - 0.5) * 0.01
+ };
+ }
+ }
+
+ private float ringR(Ctx c) {
+ return c.outerEnabled ? c.outerR : c.ir;
+ }
+
+ private float ringG(Ctx c) {
+ return c.outerEnabled ? c.outerG : c.ig;
+ }
+
+ private float ringB(Ctx c) {
+ return c.outerEnabled ? c.outerB : c.ib;
+ }
+
+ private static float sin(double v) {
+ return (float) Math.sin(v);
+ }
+
+ private void renderSwayingAccents(Ctx c, float r, float g, float b, float a, float height) {
+ if (height <= 0.1f) return;
+ float rotRad = (float) Math.toRadians(c.rotation * 0.2f);
+ Tessellator tess = Tessellator.instance;
+
+ if (c.shape == ZoneShape.SQUARE) {
+ renderSquareSwayingAccents(c, r, g, b, a, height, rotRad, tess);
+ } else {
+ for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
+ float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
+ double lx = Math.cos(baseAngle) * c.radius;
+ double lz = Math.sin(baseAngle) * c.radius;
+
+ float swayX = 0.15f * sin(c.time * 0.08f + i * 1.7f);
+ float swayZ = 0.15f * sin(c.time * 0.06f + i * 2.3f);
+
+ tess.startDrawing(GL11.GL_LINES);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(lx, 0.01, lz);
+ tess.setColorRGBA_F(r, g, b, 0.0f);
+ tess.addVertex(lx + swayX, height, lz + swayZ);
+ tess.draw();
+ }
+ }
+ }
+
+ private void renderSquareSwayingAccents(Ctx c, float r, float g, float b, float a, float height, float rotRad, Tessellator tess) {
+ int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
+ int idx = 0;
+ for (int side = 0; side < 4; side++) {
+ for (int j = 0; j < perSide; j++) {
+ float frac = (j + 0.5f) / perSide;
+ double lx, lz;
+ switch (side) {
+ case 0:
+ lx = -c.radius + frac * 2 * c.radius;
+ lz = -c.radius;
+ break;
+ case 1:
+ lx = c.radius;
+ lz = -c.radius + frac * 2 * c.radius;
+ break;
+ case 2:
+ lx = c.radius - frac * 2 * c.radius;
+ lz = c.radius;
+ break;
+ default:
+ lx = -c.radius;
+ lz = c.radius - frac * 2 * c.radius;
+ break;
+ }
+ float swayX = 0.15f * sin(c.time * 0.08f + idx * 1.7f);
+ float swayZ = 0.15f * sin(c.time * 0.06f + idx * 2.3f);
+
+ tess.startDrawing(GL11.GL_LINES);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(lx, 0.01, lz);
+ tess.setColorRGBA_F(r, g, b, 0.0f);
+ tess.addVertex(lx + swayX, height, lz + swayZ);
+ tess.draw();
+ idx++;
+ }
+ }
+ }
+
+ private void renderFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height) {
+ if (height <= 0.1f) return;
+ float rotRad = (float) Math.toRadians(c.rotation * 0.4f);
+ Tessellator tess = Tessellator.instance;
+
+ if (c.shape == ZoneShape.SQUARE) {
+ renderSquareFlickeringAccents(c, r, g, b, baseAlpha, height, tess);
+ } else {
+ for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
+ float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
+ double lx = Math.cos(baseAngle) * c.radius;
+ double lz = Math.sin(baseAngle) * c.radius;
+
+ float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + i * 3.14f));
+ float lineAlpha = baseAlpha * flicker;
+ float lineHeight = height * (0.6f + 0.4f * flicker);
+
+ tess.startDrawing(GL11.GL_LINES);
+ tess.setColorRGBA_F(r, g, b, lineAlpha);
+ tess.addVertex(lx, 0.01, lz);
+ tess.setColorRGBA_F(r, g, b, 0.0f);
+ tess.addVertex(lx, lineHeight, lz);
+ tess.draw();
+ }
+ }
+ }
+
+ private void renderSquareFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height, Tessellator tess) {
+ int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
+ int idx = 0;
+ for (int side = 0; side < 4; side++) {
+ for (int j = 0; j < perSide; j++) {
+ float frac = (j + 0.5f) / perSide;
+ double lx, lz;
+ switch (side) {
+ case 0:
+ lx = -c.radius + frac * 2 * c.radius;
+ lz = -c.radius;
+ break;
+ case 1:
+ lx = c.radius;
+ lz = -c.radius + frac * 2 * c.radius;
+ break;
+ case 2:
+ lx = c.radius - frac * 2 * c.radius;
+ lz = c.radius;
+ break;
+ default:
+ lx = -c.radius;
+ lz = c.radius - frac * 2 * c.radius;
+ break;
+ }
+ float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + idx * 3.14f));
+ float lineAlpha = baseAlpha * flicker;
+ float lineHeight = height * (0.6f + 0.4f * flicker);
+
+ tess.startDrawing(GL11.GL_LINES);
+ tess.setColorRGBA_F(r, g, b, lineAlpha);
+ tess.addVertex(lx, 0.01, lz);
+ tess.setColorRGBA_F(r, g, b, 0.0f);
+ tess.addVertex(lx, lineHeight, lz);
+ tess.draw();
+ idx++;
+ }
+ }
+ }
+
+ private double[] randomPosInZone(Ctx c) {
+ if (c.shape == ZoneShape.SQUARE) {
+ double px = (RANDOM.nextDouble() * 2 - 1) * c.radius;
+ double pz = (RANDOM.nextDouble() * 2 - 1) * c.radius;
+ return new double[]{px, 0, pz};
+ } else {
+ double angle = RANDOM.nextDouble() * Math.PI * 2;
+ double dist = Math.sqrt(RANDOM.nextDouble()) * c.radius;
+ double px = Math.cos(angle) * dist;
+ double pz = Math.sin(angle) * dist;
+ return new double[]{px, 0, pz};
+ }
+ }
+
+ private double[] randomEdgePos(Ctx c) {
+ if (c.shape == ZoneShape.SQUARE) {
+ int side = RANDOM.nextInt(4);
+ double frac = RANDOM.nextDouble() * 2 - 1;
+ switch (side) {
+ case 0:
+ return new double[]{frac * c.radius, -c.radius};
+ case 1:
+ return new double[]{frac * c.radius, c.radius};
+ case 2:
+ return new double[]{-c.radius, frac * c.radius};
+ default:
+ return new double[]{c.radius, frac * c.radius};
+ }
+ } else {
+ double angle = RANDOM.nextDouble() * Math.PI * 2;
+ double dist = c.radius * (0.5 + RANDOM.nextDouble() * 0.5);
+ return new double[]{Math.cos(angle) * dist, Math.sin(angle) * dist};
+ }
+ }
+
+ private void spawnParticle(EntityAbilityZone zone, double offsetX, double offsetY, double offsetZ,
+ double mx, double my, double mz,
+ float r, float g, float b, float alpha,
+ float scale, int maxAge, float gravity, boolean glow) {
+ ZoneParticleFX particle = new ZoneParticleFX(
+ zone.worldObj,
+ zone.posX + offsetX, zone.posY + offsetY, zone.posZ + offsetZ,
+ mx, my, mz, r, g, b, alpha, scale, maxAge, gravity, glow);
+ Minecraft.getMinecraft().effectRenderer.addEffect(particle);
+ }
+
+ private void setupRenderState() {
+ GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
+ GL11.glDisable(GL11.GL_TEXTURE_2D);
+ GL11.glDisable(GL11.GL_CULL_FACE);
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+ GL11.glDisable(GL11.GL_LIGHTING);
+ GL11.glShadeModel(GL11.GL_SMOOTH);
+ OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
+ }
+
+ private void restoreRenderState() {
+ GL11.glShadeModel(GL11.GL_FLAT);
+ GL11.glEnable(GL11.GL_LIGHTING);
+ GL11.glDisable(GL11.GL_BLEND);
+ GL11.glEnable(GL11.GL_CULL_FACE);
+ GL11.glEnable(GL11.GL_TEXTURE_2D);
+ GL11.glPopAttrib();
+ }
+
+ private void renderShapeFill(ZoneShape shape, float radius, float r, float g, float b, float a) {
+ GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
+ GL11.glPolygonOffset(-1.0f, -1.0f);
+ switch (shape) {
+ case CIRCLE:
+ renderCircleFill(radius, r, g, b, a);
+ break;
+ case SQUARE:
+ renderSquareFill(radius, r, g, b, a);
+ break;
+ }
+ GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
+ }
+
+ private void renderCircleFill(float radius, float r, float g, float b, float a) {
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawing(GL11.GL_TRIANGLE_FAN);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(0, 0, 0);
+ for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
+ double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
+ tess.addVertex(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);
+ }
+ tess.draw();
+ }
+
+ private void renderSquareFill(float radius, float r, float g, float b, float a) {
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawing(GL11.GL_QUADS);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(-radius, 0, -radius);
+ tess.addVertex(radius, 0, -radius);
+ tess.addVertex(radius, 0, radius);
+ tess.addVertex(-radius, 0, radius);
+ tess.draw();
+ }
+
+ private void renderRingLine(ZoneShape shape, float radius,
+ float r, float g, float b, float a, float yOffset) {
+ switch (shape) {
+ case CIRCLE:
+ renderCircleRingLine(radius, r, g, b, a, yOffset);
+ break;
+ case SQUARE:
+ renderSquareRingLine(radius, r, g, b, a, yOffset);
+ break;
+ }
+ }
+
+ private void renderCircleRingLine(float radius, float r, float g, float b, float a, float yOffset) {
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawing(GL11.GL_LINE_LOOP);
+ tess.setColorRGBA_F(r, g, b, a);
+ for (int i = 0; i < CIRCLE_SEGMENTS; i++) {
+ double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
+ tess.addVertex(Math.cos(angle) * radius, yOffset, Math.sin(angle) * radius);
+ }
+ tess.draw();
+ }
+
+ private void renderSquareRingLine(float radius, float r, float g, float b, float a, float yOffset) {
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawing(GL11.GL_LINE_LOOP);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(-radius, yOffset, -radius);
+ tess.addVertex(radius, yOffset, -radius);
+ tess.addVertex(radius, yOffset, radius);
+ tess.addVertex(-radius, yOffset, radius);
+ tess.draw();
+ }
+
+ private void renderRotatingBorder(ZoneShape shape, float radius,
+ float r, float g, float b, float a,
+ float rotationDeg, float yOffset) {
+ int dashCount = 16;
+
+ if (shape == ZoneShape.SQUARE) {
+ float perimeter = radius * 8;
+ float dashLen = perimeter / dashCount;
+ float offset = (rotationDeg % 360.0f) / 360.0f * perimeter;
+
+ Tessellator tess = Tessellator.instance;
+ for (int i = 0; i < dashCount; i += 2) {
+ float startDist = (i * dashLen + offset) % perimeter;
+ float endDist = startDist + dashLen;
+
+ tess.startDrawing(GL11.GL_LINE_STRIP);
+ tess.setColorRGBA_F(r, g, b, a);
+ int steps = 4;
+ for (int s = 0; s <= steps; s++) {
+ float d = startDist + (endDist - startDist) * s / steps;
+ double[] pos = perimeterPos(d % perimeter, radius);
+ tess.addVertex(pos[0], yOffset, pos[1]);
+ }
+ tess.draw();
+ }
+ } else {
+ float dashAngle = (float) (Math.PI * 2) / dashCount;
+ float rotRad = (float) Math.toRadians(rotationDeg);
+
+ Tessellator tess = Tessellator.instance;
+ for (int i = 0; i < dashCount; i += 2) {
+ float startAngle = i * dashAngle + rotRad;
+ float endAngle = startAngle + dashAngle;
+
+ tess.startDrawing(GL11.GL_LINE_STRIP);
+ tess.setColorRGBA_F(r, g, b, a);
+ int steps = 4;
+ for (int s = 0; s <= steps; s++) {
+ float segAngle = startAngle + (endAngle - startAngle) * s / steps;
+ tess.addVertex(Math.cos(segAngle) * radius, yOffset, Math.sin(segAngle) * radius);
+ }
+ tess.draw();
+ }
+ }
+ }
+
+ private double[] perimeterPos(float dist, float radius) {
+ float sideLen = radius * 2;
+ if (dist < sideLen) {
+ // Bottom edge: (-radius, -radius) to (radius, -radius)
+ return new double[]{-radius + dist, -radius};
+ }
+ dist -= sideLen;
+ if (dist < sideLen) {
+ // Right edge: (radius, -radius) to (radius, radius)
+ return new double[]{radius, -radius + dist};
+ }
+ dist -= sideLen;
+ if (dist < sideLen) {
+ // Top edge: (radius, radius) to (-radius, radius)
+ return new double[]{radius - dist, radius};
+ }
+ dist -= sideLen;
+ // Left edge: (-radius, radius) to (-radius, -radius)
+ return new double[]{-radius, radius - dist};
+ }
+
+ private void renderVerticalAccents(ZoneShape shape, float radius,
+ float r, float g, float b, float a,
+ float height, float rotationDeg) {
+ if (height <= 0.1f) return;
+
+ Tessellator tess = Tessellator.instance;
+
+ if (shape == ZoneShape.SQUARE) {
+ int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
+ for (int side = 0; side < 4; side++) {
+ for (int j = 0; j < perSide; j++) {
+ float frac = (j + 0.5f) / perSide;
+ double lx, lz;
+ switch (side) {
+ case 0:
+ lx = -radius + frac * 2 * radius;
+ lz = -radius;
+ break;
+ case 1:
+ lx = radius;
+ lz = -radius + frac * 2 * radius;
+ break;
+ case 2:
+ lx = radius - frac * 2 * radius;
+ lz = radius;
+ break;
+ default:
+ lx = -radius;
+ lz = radius - frac * 2 * radius;
+ break;
+ }
+ tess.startDrawing(GL11.GL_LINES);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(lx, 0.01, lz);
+ tess.setColorRGBA_F(r, g, b, 0.0f);
+ tess.addVertex(lx, height, lz);
+ tess.draw();
+ }
+ }
+ float[][] corners = {{-radius, -radius}, {radius, -radius}, {radius, radius}, {-radius, radius}};
+ for (float[] corner : corners) {
+ tess.startDrawing(GL11.GL_LINES);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(corner[0], 0.01, corner[1]);
+ tess.setColorRGBA_F(r, g, b, 0.0f);
+ tess.addVertex(corner[0], height, corner[1]);
+ tess.draw();
+ }
+ } else {
+ float rotRad = (float) Math.toRadians(rotationDeg);
+ for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
+ float angle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
+ double lx = Math.cos(angle) * radius;
+ double lz = Math.sin(angle) * radius;
+
+ tess.startDrawing(GL11.GL_LINES);
+ tess.setColorRGBA_F(r, g, b, a);
+ tess.addVertex(lx, 0.01, lz);
+ tess.setColorRGBA_F(r, g, b, 0.0f);
+ tess.addVertex(lx, height, lz);
+ tess.draw();
+ }
+ }
+ }
+
+ @Override
+ protected ResourceLocation getEntityTexture(Entity entity) {
+ return null;
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java
index 3b5e49e2d..dc653e73f 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java
@@ -105,11 +105,14 @@ public class TelegraphRenderer {
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
break;
case CONE:
- renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha);
+ renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha);
break;
case POINT:
renderPoint(red, green, blue, alpha);
break;
+ case SQUARE:
+ renderSquare(telegraph.getRadius(), red, green, blue, alpha);
+ break;
default:
break;
}
@@ -204,42 +207,98 @@ public class TelegraphRenderer {
tessellator.draw();
}
- private void renderCone(float length, float angle, float r, float g, float b, float a) {
+ private void renderCone(float length, float angle, float innerRadius, float r, float g, float b, float a) {
float halfAngleRad = (float) Math.toRadians(angle / 2);
Tessellator tessellator = Tessellator.instance;
- tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
- tessellator.setColorRGBA_F(r, g, b, a);
- // Origin point
- tessellator.addVertex(0, 0, 0);
+ if (innerRadius <= 0) {
+ // Standard cone: triangle fan from origin
+ tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
+ tessellator.setColorRGBA_F(r, g, b, a);
- // Arc points
- for (int i = 0; i <= CONE_SEGMENTS; i++) {
- float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
- double x = Math.sin(segmentAngle) * length;
- double z = Math.cos(segmentAngle) * length;
- tessellator.addVertex(x, 0, z);
+ tessellator.addVertex(0, 0, 0);
+
+ for (int i = 0; i <= CONE_SEGMENTS; i++) {
+ float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
+ double x = Math.sin(segmentAngle) * length;
+ double z = Math.cos(segmentAngle) * length;
+ tessellator.addVertex(x, 0, z);
+ }
+
+ tessellator.draw();
+
+ // Border
+ tessellator.startDrawing(GL11.GL_LINE_STRIP);
+ tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
+
+ tessellator.addVertex(0, 0.01, 0);
+
+ for (int i = 0; i <= CONE_SEGMENTS; i++) {
+ float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
+ double x = Math.sin(segmentAngle) * length;
+ double z = Math.cos(segmentAngle) * length;
+ tessellator.addVertex(x, 0.01, z);
+ }
+
+ tessellator.addVertex(0, 0.01, 0);
+
+ tessellator.draw();
+ } else {
+ // Truncated cone: strip between inner and outer arcs
+ tessellator.startDrawing(GL11.GL_TRIANGLE_STRIP);
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ for (int i = 0; i <= CONE_SEGMENTS; i++) {
+ float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
+ double sinA = Math.sin(segmentAngle);
+ double cosA = Math.cos(segmentAngle);
+
+ tessellator.addVertex(sinA * length, 0, cosA * length);
+ tessellator.addVertex(sinA * innerRadius, 0, cosA * innerRadius);
+ }
+
+ tessellator.draw();
+
+ // Border: outer arc
+ float borderAlpha = Math.min(1.0f, a * 2);
+ tessellator.startDrawing(GL11.GL_LINE_STRIP);
+ tessellator.setColorRGBA_F(r, g, b, borderAlpha);
+
+ for (int i = 0; i <= CONE_SEGMENTS; i++) {
+ float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
+ tessellator.addVertex(Math.sin(segmentAngle) * length, 0.01, Math.cos(segmentAngle) * length);
+ }
+
+ tessellator.draw();
+
+ // Border: inner arc
+ tessellator.startDrawing(GL11.GL_LINE_STRIP);
+ tessellator.setColorRGBA_F(r, g, b, borderAlpha);
+
+ for (int i = 0; i <= CONE_SEGMENTS; i++) {
+ float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
+ tessellator.addVertex(Math.sin(segmentAngle) * innerRadius, 0.01, Math.cos(segmentAngle) * innerRadius);
+ }
+
+ tessellator.draw();
+
+ // Border: side edges connecting inner and outer arcs
+ tessellator.startDrawing(GL11.GL_LINES);
+ tessellator.setColorRGBA_F(r, g, b, borderAlpha);
+
+ double sinStart = Math.sin(-halfAngleRad);
+ double cosStart = Math.cos(-halfAngleRad);
+ tessellator.addVertex(sinStart * innerRadius, 0.01, cosStart * innerRadius);
+ tessellator.addVertex(sinStart * length, 0.01, cosStart * length);
+
+ double sinEnd = Math.sin(halfAngleRad);
+ double cosEnd = Math.cos(halfAngleRad);
+ tessellator.addVertex(sinEnd * innerRadius, 0.01, cosEnd * innerRadius);
+ tessellator.addVertex(sinEnd * length, 0.01, cosEnd * length);
+
+ tessellator.draw();
}
-
- tessellator.draw();
-
- // Draw border
- tessellator.startDrawing(GL11.GL_LINE_STRIP);
- tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
-
- tessellator.addVertex(0, 0.01, 0);
-
- for (int i = 0; i <= CONE_SEGMENTS; i++) {
- float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
- double x = Math.sin(segmentAngle) * length;
- double z = Math.cos(segmentAngle) * length;
- tessellator.addVertex(x, 0.01, z);
- }
-
- tessellator.addVertex(0, 0.01, 0);
-
- tessellator.draw();
}
private void renderPoint(float r, float g, float b, float a) {
@@ -258,6 +317,30 @@ public class TelegraphRenderer {
tessellator.draw();
}
+ private void renderSquare(float radius, float r, float g, float b, float a) {
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawingQuads();
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ tessellator.addVertex(-radius, 0, -radius);
+ tessellator.addVertex(radius, 0, -radius);
+ tessellator.addVertex(radius, 0, radius);
+ tessellator.addVertex(-radius, 0, radius);
+
+ tessellator.draw();
+
+ // Draw border
+ tessellator.startDrawing(GL11.GL_LINE_LOOP);
+ tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
+
+ tessellator.addVertex(-radius, 0.01, -radius);
+ tessellator.addVertex(radius, 0.01, -radius);
+ tessellator.addVertex(radius, 0.01, radius);
+ tessellator.addVertex(-radius, 0.01, radius);
+
+ tessellator.draw();
+ }
+
// ==================== GUI PREVIEW RENDERING ====================
/**
@@ -272,8 +355,8 @@ public class TelegraphRenderer {
* @param partialTicks Partial ticks for interpolation
*/
public void renderTelegraphInGUI(TelegraphInstance instance,
- double centerX, double centerY, double centerZ,
- float scale, float partialTicks) {
+ double centerX, double centerY, double centerZ,
+ float scale, float partialTicks) {
if (instance == null) return;
Telegraph telegraph = instance.getTelegraph();
@@ -317,11 +400,14 @@ public class TelegraphRenderer {
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
break;
case CONE:
- renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha);
+ renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha);
break;
case POINT:
renderPoint(red, green, blue, alpha);
break;
+ case SQUARE:
+ renderSquare(telegraph.getRadius(), red, green, blue, alpha);
+ break;
default:
break;
}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java
index d68c4037b..4debb90d6 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java
@@ -3,7 +3,6 @@ package kamkeel.npcs.client.renderer.lightning;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.opengl.GL11;
-import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -37,6 +36,7 @@ public class AttachedLightningRenderer {
public float getAlphaMultiplier() {
// Fade out over lifetime
+ if (maxAge <= 0) return 0.0f;
return 1.0f - ((float) age / (float) maxAge);
}
@@ -85,6 +85,28 @@ public class AttachedLightningRenderer {
}
}
+ /**
+ * Age existing arcs and remove dead ones without spawning new arcs.
+ * Use with addArc() for custom arc generation.
+ */
+ public void tick() {
+ Iterator iter = arcs.iterator();
+ while (iter.hasNext()) {
+ LightningArc arc = iter.next();
+ arc.tick();
+ if (arc.isDead()) {
+ iter.remove();
+ }
+ }
+ }
+
+ /**
+ * Add a custom arc to the state.
+ */
+ public void addArc(LightningArc arc) {
+ arcs.add(arc);
+ }
+
/**
* Render all active arcs in local space.
* Call this after glTranslated to entity position.
@@ -143,8 +165,8 @@ public class AttachedLightningRenderer {
* Generate a jagged lightning path between two points.
*/
private static List generateLightningPath(double x1, double y1, double z1,
- double x2, double y2, double z2,
- int segments, float displacement) {
+ double x2, double y2, double z2,
+ int segments, float displacement) {
List points = new ArrayList<>();
points.add(new double[]{x1, y1, z1});
@@ -186,10 +208,9 @@ public class AttachedLightningRenderer {
private static void renderBoltPath(Tessellator tess, List points, int color, float width, float alpha) {
if (alpha <= 0.01f) return;
- Color c = new Color(color);
- int r = c.getRed();
- int g = c.getGreen();
- int b = c.getBlue();
+ int r = (color >> 16) & 0xFF;
+ int g = (color >> 8) & 0xFF;
+ int b = color & 0xFF;
int a = Math.min(255, Math.max(0, (int) (alpha * 255)));
for (int i = 0; i < points.size() - 1; i++) {
@@ -231,6 +252,17 @@ public class AttachedLightningRenderer {
}
}
+ /**
+ * Create a lightning arc between two arbitrary points.
+ */
+ public static LightningArc createArcBetween(double x1, double y1, double z1,
+ double x2, double y2, double z2,
+ float displacement, int outerColor, int innerColor, int maxAge) {
+ int segments = 4 + rand.nextInt(3);
+ List points = generateLightningPath(x1, y1, z1, x2, y2, z2, segments, displacement);
+ return new LightningArc(points, maxAge, outerColor, innerColor);
+ }
+
// ==================== INSTANT RENDERING (no persistence) ====================
/**
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java
index 6cf6e7d3a..beea63fd3 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java
@@ -56,7 +56,7 @@ public class LightningBolt {
this.numSegments0 = 1;
this.length = end.copy().subtract(start).mag();
- this.particleMaxAge = FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2;
+ this.particleMaxAge = Math.max(1, FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2);
this.particleAge = -(int) (length * speed);
segments.add(new Segment(start, end));
@@ -243,7 +243,7 @@ public class LightningBolt {
public Segment(Vec3d start, Vec3d end) {
this(new BoltPoint(start, new Vec3d(0, 0, 0)),
- new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0);
+ new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0);
}
public void calcDiff() {
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java
index 1951666e4..d3f9aeedd 100644
--- a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java
@@ -5,7 +5,6 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.LightningBolt.Segment;
import net.minecraft.client.Minecraft;
-import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.entity.Entity;
@@ -19,7 +18,7 @@ import java.awt.Color;
/**
* Handles rendering of lightning bolts in the world.
* Adapted from Botania's LightningHandler by Vazkii/ChickenBones.
- *
+ *
* Register this handler with: MinecraftForge.EVENT_BUS.register(new LightningHandler());
*/
@SideOnly(Side.CLIENT)
@@ -168,13 +167,13 @@ public class LightningHandler {
/**
* Spawn a lightning bolt between two points.
*
- * @param world The world
- * @param start Start position
- * @param end End position
+ * @param world The world
+ * @param start Start position
+ * @param end End position
* @param ticksPerMeter Speed of bolt expansion
- * @param seed Random seed for consistent appearance
- * @param colorOuter Outer glow color (ARGB)
- * @param colorInner Inner core color (ARGB)
+ * @param seed Random seed for consistent appearance
+ * @param colorOuter Outer glow color (ARGB)
+ * @param colorInner Inner core color (ARGB)
*/
public static void spawnLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, long seed, int colorOuter, int colorInner) {
LightningBolt bolt = new LightningBolt(world, start, end, ticksPerMeter, seed, colorOuter, colorInner);
diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java
index 004274fc3..982a975b3 100644
--- a/src/main/java/kamkeel/npcs/command/AbilityCommand.java
+++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java
@@ -1,12 +1,14 @@
package kamkeel.npcs.command;
+import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
-import kamkeel.npcs.controllers.data.ability.AbilityController;
-import kamkeel.npcs.controllers.data.ability.UserType;
+import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
+import kamkeel.npcs.controllers.data.ability.enums.UserType;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.controllers.PlayerDataController;
+import noppes.npcs.controllers.data.PlayerAbilityData;
import noppes.npcs.controllers.data.PlayerData;
import java.util.ArrayList;
@@ -33,20 +35,19 @@ public class AbilityCommand extends CommandKamkeelBase {
desc = "List all custom abilities"
)
public void list(ICommandSender sender, String[] args) {
- Set uuids = AbilityController.Instance.getCustomAbilityIds();
- if (uuids.isEmpty()) {
+ Set names = AbilityController.Instance.getCustomAbilityNames();
+ if (names.isEmpty()) {
sendResult(sender, "No custom abilities found.");
return;
}
- sendResult(sender, "Custom Abilities (" + uuids.size() + "):");
- for (String uuid : uuids) {
- Ability ability = AbilityController.Instance.getCustomAbility(uuid);
+ sendResult(sender, "Custom Abilities (" + names.size() + "):");
+ for (String name : names) {
+ Ability ability = AbilityController.Instance.getCustomAbility(name);
if (ability != null) {
- String name = ability.getName() != null ? ability.getName() : uuid;
- sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ") [" + uuid + "]");
+ sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ")");
} else {
- sendResult(sender, " - \u00A7b" + uuid);
+ sendResult(sender, " - \u00A7b" + name);
}
}
}
@@ -78,27 +79,27 @@ public class AbilityCommand extends CommandKamkeelBase {
)
public void reload(ICommandSender sender, String[] args) {
AbilityController.Instance.load();
- sendResult(sender, "Abilities reloaded from disk.");
+ sendResult(sender, "Abilities and chained abilities reloaded from disk.");
}
@SubCommand(
- desc = "Delete a custom ability by UUID",
- usage = ""
+ desc = "Delete a custom ability by name",
+ usage = ""
)
public void delete(ICommandSender sender, String[] args) {
if (args.length < 1) {
- sendError(sender, "Usage: /kam ability delete ");
+ sendError(sender, "Usage: /kam ability delete ");
return;
}
- String uuid = args[0];
- if (!AbilityController.Instance.hasCustomAbility(uuid)) {
- sendError(sender, "No custom ability with UUID: " + uuid);
+ String name = joinArgs(args, 0);
+ if (!AbilityController.Instance.hasCustomAbilityName(name)) {
+ sendError(sender, "No custom ability with name: " + name);
return;
}
- AbilityController.Instance.deleteCustomAbility(uuid);
- sendResult(sender, "Deleted ability: \u00A7b" + uuid);
+ AbilityController.Instance.deleteCustomAbility(name);
+ sendResult(sender, "Deleted ability: \u00A7b" + name);
}
@SubCommand(
@@ -111,14 +112,15 @@ public class AbilityCommand extends CommandKamkeelBase {
return;
}
- String key = args[0];
+ String key = joinArgs(args, 0);
Ability ability = AbilityController.Instance.resolveAbility(key);
if (ability == null) {
sendError(sender, "No ability found for: " + key);
return;
}
- sendResult(sender, "Ability: \u00A7b" + ability.getName());
+ sendResult(sender, "Ability: \u00A7b" + ability.getDisplayName());
+ sendResult(sender, " Name: \u00A77" + ability.getName());
sendResult(sender, " Type: \u00A7d" + ability.getTypeId());
sendResult(sender, " Cooldown: \u00A7e" + ability.getCooldownTicks() + " ticks");
sendResult(sender, " Wind Up: \u00A7e" + ability.getWindUpTicks() + " ticks");
@@ -163,26 +165,24 @@ public class AbilityCommand extends CommandKamkeelBase {
}
@SubCommand(
- desc = "Unlock an ability for a player",
+ desc = "Give an ability to a player",
usage = " "
)
- public void unlock(ICommandSender sender, String[] args) {
+ public void give(ICommandSender sender, String[] args) {
if (args.length < 2) {
- sendError(sender, "Usage: /kam ability unlock ");
+ sendError(sender, "Usage: /kam ability give ");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
- // Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
- // Resolve ability
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
if (ability == null) {
sendError(sender, "Ability not found: " + abilityKey);
@@ -192,17 +192,15 @@ public class AbilityCommand extends CommandKamkeelBase {
// Use the ability's canonical ID for storage (registry key for built-in, UUID for custom)
String canonicalKey = ability.getId();
if (canonicalKey == null || canonicalKey.isEmpty()) {
- canonicalKey = abilityKey; // Fallback to user-provided key
+ canonicalKey = abilityKey;
}
- String displayName = ability.getName() != null ? ability.getName() : canonicalKey;
+ String displayName = ability.getDisplayName();
- // Check if ability allows players
if (!ability.getAllowedBy().allowsPlayer()) {
sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players.");
return;
}
- // Get player data and unlock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player already has ability: " + displayName);
@@ -210,39 +208,36 @@ public class AbilityCommand extends CommandKamkeelBase {
}
data.abilityData.unlockAbility(canonicalKey);
- sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName);
+ sendResult(sender, "Gave ability '\u00A7b" + displayName + "\u00A77' to player \u00A7a" + playerName);
}
@SubCommand(
- desc = "Lock (revoke) an ability from a player",
+ desc = "Remove an ability from a player",
usage = " "
)
- public void lock(ICommandSender sender, String[] args) {
+ public void remove(ICommandSender sender, String[] args) {
if (args.length < 2) {
- sendError(sender, "Usage: /kam ability lock ");
+ sendError(sender, "Usage: /kam ability remove ");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
- // Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
- // Resolve ability to get canonical key
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
- String canonicalKey = abilityKey;
- String displayName = abilityKey;
- if (ability != null) {
- canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
- displayName = ability.getName() != null ? ability.getName() : canonicalKey;
+ if (ability == null) {
+ sendError(sender, "Ability not found: " + abilityKey);
+ return;
}
+ String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
+ String displayName = ability.getDisplayName();
- // Get player data and lock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (!data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player doesn't have ability: " + displayName);
@@ -250,7 +245,98 @@ public class AbilityCommand extends CommandKamkeelBase {
}
data.abilityData.lockAbility(canonicalKey);
- sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName);
+ sendResult(sender, "Removed ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName);
+ }
+
+ @SubCommand(
+ desc = "Give a chained ability to a player",
+ usage = " "
+ )
+ public void giveChain(ICommandSender sender, String[] args) {
+ if (args.length < 2) {
+ sendError(sender, "Usage: /kam ability giveChain ");
+ return;
+ }
+
+ String playerName = args[0];
+ String chainKey = joinArgs(args, 1);
+
+ EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
+ if (player == null) {
+ sendError(sender, "Player not found: " + playerName);
+ return;
+ }
+
+ ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey);
+ if (chain == null) {
+ sendError(sender, "Chained ability not found: " + chainKey);
+ return;
+ }
+
+ if (!chain.getAllowedBy().allowsPlayer()) {
+ sendError(sender, "Chained ability '\u00A7b" + chain.getDisplayName() + "\u00A7c' is NPC-only and cannot be given to players.");
+ return;
+ }
+
+ String chainId = chain.getId();
+ if (chainId == null || chainId.isEmpty()) {
+ sendError(sender, "Chained ability has no ID: " + chain.getDisplayName());
+ return;
+ }
+
+ // Store by UUID: chain:
+ String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId;
+ PlayerData data = PlayerDataController.Instance.getPlayerData(player);
+ if (data.abilityData.hasUnlockedAbility(storageKey)) {
+ sendError(sender, "Player already has chained ability: " + chain.getDisplayName());
+ return;
+ }
+
+ data.abilityData.unlockAbility(storageKey);
+ sendResult(sender, "Gave chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' to player \u00A7a" + playerName);
+ }
+
+ @SubCommand(
+ desc = "Remove a chained ability from a player",
+ usage = " "
+ )
+ public void removeChain(ICommandSender sender, String[] args) {
+ if (args.length < 2) {
+ sendError(sender, "Usage: /kam ability removeChain ");
+ return;
+ }
+
+ String playerName = args[0];
+ String chainKey = joinArgs(args, 1);
+
+ EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
+ if (player == null) {
+ sendError(sender, "Player not found: " + playerName);
+ return;
+ }
+
+ ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey);
+ if (chain == null) {
+ sendError(sender, "Chained ability not found: " + chainKey);
+ return;
+ }
+
+ String chainId = chain.getId();
+ if (chainId == null || chainId.isEmpty()) {
+ sendError(sender, "Chained ability has no ID: " + chain.getDisplayName());
+ return;
+ }
+
+ // Storage uses UUID: chain:
+ String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId;
+ PlayerData data = PlayerDataController.Instance.getPlayerData(player);
+ if (!data.abilityData.hasUnlockedAbility(storageKey)) {
+ sendError(sender, "Player doesn't have chained ability: " + chain.getDisplayName());
+ return;
+ }
+
+ data.abilityData.lockAbility(storageKey);
+ sendResult(sender, "Removed chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' from player \u00A7a" + playerName);
}
@SubCommand(
@@ -284,14 +370,23 @@ public class AbilityCommand extends CommandKamkeelBase {
int selected = data.abilityData.getSelectedIndex();
for (int i = 0; i < abilityKeys.length; i++) {
String key = abilityKeys[i];
- Ability ability = AbilityController.Instance.resolveAbility(key);
- String displayName = ability != null && ability.getName() != null ? ability.getName() : key;
String prefix = (i == selected) ? "\u00A7e> " : " ";
- // Show display name and key if different
- if (!displayName.equals(key)) {
- sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]");
+
+ if (key.startsWith(PlayerAbilityData.CHAIN_PREFIX)) {
+ // Chained ability
+ String chainName = key.substring(PlayerAbilityData.CHAIN_PREFIX.length());
+ ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainName);
+ String display = chain != null ? chain.getDisplayName() : chainName;
+ sendResult(sender, prefix + "\u00A7d[Chain] \u00A7b" + display);
} else {
- sendResult(sender, prefix + "\u00A7b" + displayName);
+ // Regular ability
+ Ability ability = AbilityController.Instance.resolveAbility(key);
+ String displayName = ability != null ? ability.getDisplayName() : key;
+ if (!displayName.equals(key)) {
+ sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]");
+ } else {
+ sendResult(sender, prefix + "\u00A7b" + displayName);
+ }
}
}
}
@@ -306,13 +401,34 @@ public class AbilityCommand extends CommandKamkeelBase {
}
/**
- * Get list of player-usable ability keys (for tab completion).
- * Uses registry keys for built-in abilities (no spaces) and UUIDs for custom.
- * Used by CommandKamkeel for usage token.
+ * Get list of player-usable ability names (for tab completion).
+ * Resolves UUIDs to names so tab completion shows human-readable names.
+ * Used by CommandKamkeel for {@code } usage token.
*/
public static List getPlayerAbilityNames() {
- List keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys());
- Collections.sort(keys);
- return keys;
+ Set keys = AbilityController.Instance.getPlayerAbilityKeys();
+ List names = new ArrayList<>();
+ for (String key : keys) {
+ Ability a = AbilityController.Instance.resolveAbility(key);
+ names.add(a != null ? a.getName() : key);
+ }
+ Collections.sort(names);
+ return names;
+ }
+
+ /**
+ * Get list of player-usable chained ability names (for tab completion).
+ * Used by CommandKamkeel for {@code } usage token.
+ */
+ public static List getPlayerChainNames() {
+ List names = new ArrayList<>();
+ for (String chainName : AbilityController.Instance.getChainedAbilityNamesSet()) {
+ ChainedAbility chain = AbilityController.Instance.getChainedAbility(chainName);
+ if (chain != null && chain.getAllowedBy().allowsPlayer()) {
+ names.add(chainName);
+ }
+ }
+ Collections.sort(names);
+ return names;
}
}
diff --git a/src/main/java/kamkeel/npcs/command/AuctionCommand.java b/src/main/java/kamkeel/npcs/command/AuctionCommand.java
index 87d7e4385..a56dce671 100644
--- a/src/main/java/kamkeel/npcs/command/AuctionCommand.java
+++ b/src/main/java/kamkeel/npcs/command/AuctionCommand.java
@@ -20,6 +20,7 @@ import static kamkeel.npcs.util.ColorUtil.sendMessage;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class AuctionCommand extends CommandKamkeelBase {
+ private static final int COMMAND_PAGE_SIZE = 10;
public AuctionCommand() {
super();
@@ -62,9 +63,10 @@ public class AuctionCommand extends CommandKamkeelBase {
}
}
- List listings = controller.getActiveListings(null, page - 1, 10);
+ page = Math.max(1, page);
+ List listings = controller.getActiveListings(null, page - 1, COMMAND_PAGE_SIZE);
int total = controller.getTotalActiveListings(null);
- int totalPages = Math.max(1, (int) Math.ceil((double) total / 10));
+ int totalPages = Math.max(1, (int) Math.ceil((double) total / COMMAND_PAGE_SIZE));
if (listings.isEmpty()) {
sendMessage(sender, "\u00A77No active auctions found");
@@ -98,6 +100,10 @@ public class AuctionCommand extends CommandKamkeelBase {
return;
}
+ if (args.length < 1) {
+ throw new CommandException("Usage: /auction view ");
+ }
+
String playername = args[0];
List dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java
index 91356c825..f87068968 100644
--- a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java
+++ b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java
@@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames;
+import static kamkeel.npcs.command.AbilityCommand.getPlayerChainNames;
import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames;
public class CommandKamkeel extends CommandBase {
@@ -51,6 +52,7 @@ public class CommandKamkeel extends CommandBase {
registerCommand(new AuctionCommand());
if (ConfigMain.AttributesEnabled)
registerCommand(new AttributeCommand());
+ registerCommand(new DebugCommand());
}
public void registerCommand(CommandKamkeelBase command) {
@@ -134,10 +136,13 @@ public class CommandKamkeel extends CommandBase {
List keys = new ArrayList<>(RequirementCheckerRegistry.getAllKeys());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("")) {
- List keys = getSortedEffectNames();
+ List keys = stripColorCodes(getSortedEffectNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("")) {
- List keys = getPlayerAbilityNames();
+ List keys = stripColorCodes(getPlayerAbilityNames());
+ return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
+ } else if (usage.equals("")) {
+ List keys = stripColorCodes(getPlayerChainNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
}
}
@@ -145,6 +150,14 @@ public class CommandKamkeel extends CommandBase {
return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length));
}
+ private static List stripColorCodes(List list) {
+ List result = new ArrayList<>(list.size());
+ for (String s : list) {
+ result.add(s.replaceAll("\u00A7[0-9a-fk-or]", ""));
+ }
+ return result;
+ }
+
public CommandKamkeelBase getCommand(String[] args) {
if (args.length == 0)
return null;
diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java b/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java
index df4d34998..c6ffe7ec1 100644
--- a/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java
+++ b/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java
@@ -11,7 +11,13 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
public abstract class CommandKamkeelBase extends CommandBase {
public Map subcommands = new HashMap();
diff --git a/src/main/java/kamkeel/npcs/command/DebugCommand.java b/src/main/java/kamkeel/npcs/command/DebugCommand.java
new file mode 100644
index 000000000..1cb497a93
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/command/DebugCommand.java
@@ -0,0 +1,41 @@
+package kamkeel.npcs.command;
+
+import kamkeel.npcs.util.CNPCDebug;
+import net.minecraft.command.CommandException;
+import net.minecraft.command.ICommandSender;
+
+import static kamkeel.npcs.util.ColorUtil.sendResult;
+
+public class DebugCommand extends CommandKamkeelBase {
+
+ @Override
+ public String getCommandName() {
+ return "debug";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Toggle debug logging types";
+ }
+
+ @Override
+ public String getUsage() {
+ return "";
+ }
+
+ @Override
+ public boolean runSubCommands() {
+ return false;
+ }
+
+ @Override
+ public void processCommand(ICommandSender sender, String[] args) throws CommandException {
+ if (args.length == 0) {
+ throw new CommandException("Usage: /kam debug (e.g. energy)");
+ }
+
+ String type = args[0].toLowerCase();
+ boolean newState = CNPCDebug.toggleServer(type);
+ sendResult(sender, "Server debug '" + type + "' " + (newState ? "\u00A7aENABLED" : "\u00A7cDISABLED"));
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/command/DialogCommand.java b/src/main/java/kamkeel/npcs/command/DialogCommand.java
index 2392859a4..d9df94c13 100644
--- a/src/main/java/kamkeel/npcs/command/DialogCommand.java
+++ b/src/main/java/kamkeel/npcs/command/DialogCommand.java
@@ -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");
}
diff --git a/src/main/java/kamkeel/npcs/command/EffectCommand.java b/src/main/java/kamkeel/npcs/command/EffectCommand.java
index 8a6a2e669..3d7cdbec8 100644
--- a/src/main/java/kamkeel/npcs/command/EffectCommand.java
+++ b/src/main/java/kamkeel/npcs/command/EffectCommand.java
@@ -308,6 +308,7 @@ public class EffectCommand extends CommandKamkeelBase {
// Helper method to find effects by name.
private List findEffectsByName(String name) {
+ String strippedName = stripColorCodes(name);
List matches = new ArrayList<>();
CustomEffectController controller = CustomEffectController.getInstance();
for (Map.Entry> entry : controller.indexMapper.entrySet()) {
@@ -317,11 +318,12 @@ public class EffectCommand extends CommandKamkeelBase {
for (Map.Entry effectEntry : effects.entrySet()) {
int id = effectEntry.getKey();
CustomEffect effect = effectEntry.getValue();
- if (effect.getName().equalsIgnoreCase(name)) {
+ String effectName = stripColorCodes(effect.getName());
+ if (effectName.equalsIgnoreCase(strippedName)) {
List exact = new ArrayList<>();
exact.add(new EffectEntry(idx, id, effect));
return exact;
- } else if (effect.getName().toLowerCase().contains(name.toLowerCase())) {
+ } else if (effectName.toLowerCase().contains(strippedName.toLowerCase())) {
matches.add(new EffectEntry(idx, id, effect));
}
}
@@ -329,6 +331,10 @@ public class EffectCommand extends CommandKamkeelBase {
return matches;
}
+ private static String stripColorCodes(String s) {
+ return s.replaceAll("\u00A7[0-9a-fk-or]", "");
+ }
+
public static List getSortedEffectNames() {
List entries = new ArrayList<>();
CustomEffectController controller = CustomEffectController.getInstance();
diff --git a/src/main/java/kamkeel/npcs/command/NpcCommand.java b/src/main/java/kamkeel/npcs/command/NpcCommand.java
index 556976ed0..74a125e19 100644
--- a/src/main/java/kamkeel/npcs/command/NpcCommand.java
+++ b/src/main/java/kamkeel/npcs/command/NpcCommand.java
@@ -200,7 +200,7 @@ public class NpcCommand extends CommandKamkeelBase {
EntityCustomNpc npc = new EntityCustomNpc(pw);
if (args.length > 0)
npc.display.name = args[0];
- npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
+ npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0);
npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
diff --git a/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java b/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java
index f33d3626b..27eb0efb8 100644
--- a/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java
+++ b/src/main/java/kamkeel/npcs/command/QuestCategoryCommand.java
@@ -99,7 +99,9 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
playerdata.questData.finishedQuests.put(quest.id, completeTime);
}
- if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
+ if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
+ && (quest.profileOptions.completeControl == EnumProfileSync.Shared
+ || quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
;
diff --git a/src/main/java/kamkeel/npcs/command/QuestCommand.java b/src/main/java/kamkeel/npcs/command/QuestCommand.java
index 0a6cb5edf..7cfd6ebe4 100644
--- a/src/main/java/kamkeel/npcs/command/QuestCommand.java
+++ b/src/main/java/kamkeel/npcs/command/QuestCommand.java
@@ -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;
@@ -115,7 +116,9 @@ public class QuestCommand extends CommandKamkeelBase {
playerdata.questData.finishedQuests.put(quest.id, completeTime);
}
- if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
+ if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
+ && (quest.profileOptions.completeControl == EnumProfileSync.Shared
+ || quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
playerdata.save();
@@ -391,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");
}
}
diff --git a/src/main/java/kamkeel/npcs/controllers/AbilityController.java b/src/main/java/kamkeel/npcs/controllers/AbilityController.java
new file mode 100644
index 000000000..66c057929
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java
@@ -0,0 +1,1532 @@
+package kamkeel.npcs.controllers;
+
+import kamkeel.npcs.controllers.data.ability.conditions.AbilityCondition;
+import kamkeel.npcs.controllers.data.ability.conditions.ConditionHPThreshold;
+import kamkeel.npcs.controllers.data.ability.conditions.ConditionHitCount;
+import kamkeel.npcs.controllers.data.ability.conditions.ConditionItem;
+import kamkeel.npcs.controllers.data.ability.conditions.ConditionHasEffect;
+import kamkeel.npcs.controllers.data.ability.conditions.ConditionQuestCompleted;
+import kamkeel.npcs.controllers.data.ability.Ability;
+import kamkeel.npcs.controllers.data.ability.AbilityVariant;
+import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
+import kamkeel.npcs.controllers.data.ability.data.effect.IEffectAction;
+import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
+import kamkeel.npcs.controllers.data.ability.data.entry.ChainedAbilityEntry;
+import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
+import kamkeel.npcs.controllers.data.ability.enums.UserType;
+import kamkeel.npcs.controllers.data.ability.extender.IAbilityExtender;
+import kamkeel.npcs.controllers.data.ability.gui.IAbilityFieldProvider;
+import kamkeel.npcs.controllers.data.ability.gui.IChainedAbilityFieldProvider;
+import kamkeel.npcs.controllers.data.ability.CustomAbility;
+import kamkeel.npcs.controllers.data.ability.type.AbilityCharge;
+import kamkeel.npcs.controllers.data.ability.type.AbilityCutter;
+import kamkeel.npcs.controllers.data.ability.type.AbilityDash;
+import kamkeel.npcs.controllers.data.ability.type.AbilityCounter;
+import kamkeel.npcs.controllers.data.ability.type.AbilityDodge;
+import kamkeel.npcs.controllers.data.ability.type.AbilityGuard;
+import kamkeel.npcs.controllers.data.ability.type.AbilityHazard;
+import kamkeel.npcs.controllers.data.ability.type.AbilityEffect;
+import kamkeel.npcs.controllers.data.ability.type.AbilityHeavyHit;
+import kamkeel.npcs.controllers.data.ability.type.AbilityShockwave;
+import kamkeel.npcs.controllers.data.ability.type.AbilitySlam;
+import kamkeel.npcs.controllers.data.ability.type.AbilityTeleport;
+import kamkeel.npcs.controllers.data.ability.type.AbilityTrap;
+import kamkeel.npcs.controllers.data.ability.type.AbilityVortex;
+import kamkeel.npcs.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;
+import kamkeel.npcs.controllers.data.ability.type.energy.AbilityLaser;
+import kamkeel.npcs.controllers.data.ability.type.energy.AbilityOrb;
+import kamkeel.npcs.controllers.data.ability.type.energy.AbilityShield;
+import kamkeel.npcs.controllers.data.ability.type.energy.AbilitySweeper;
+import kamkeel.npcs.controllers.data.ability.type.energy.AbilityWall;
+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;
+import noppes.npcs.api.ability.IChainedAbility;
+import noppes.npcs.api.handler.IAbilityHandler;
+import noppes.npcs.controllers.PlayerDataController;
+import noppes.npcs.controllers.CategoryManager;
+import noppes.npcs.controllers.TagController;
+import noppes.npcs.controllers.data.PlayerData;
+import noppes.npcs.util.NBTJsonUtil;
+import kamkeel.npcs.util.FileNameHelper;
+
+import java.io.File;
+import java.util.*;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+
+public class AbilityController implements IAbilityHandler {
+
+ public static AbilityController Instance = new AbilityController();
+
+ // ── Core Registries ──────────────────────────────────────────────────────
+ private final Map> abilityTypes = new LinkedHashMap<>();
+ private final Map builtAbilities = new LinkedHashMap<>();
+ private final Map customAbilities = new LinkedHashMap<>(); // name → Ability
+ private final Map customAbilitiesById = new LinkedHashMap<>(); // UUID → Ability
+
+ // ── Script Handlers ────────────────────────────────────────────────────
+ public final HashMap abilityScriptHandlers = new HashMap<>();
+ public final HashMap chainedAbilityScriptHandlers = new HashMap<>();
+
+ // ── Extension Points ─────────────────────────────────────────────────────
+ private final Map> externalVariants = new LinkedHashMap<>();
+ private final List fieldProviders = new ArrayList<>();
+ private final List chainedFieldProviders = new ArrayList<>();
+ private final List extenders = new ArrayList<>();
+ private final Map> conditionTypes = new HashMap<>();
+ private final List> flightCheckers = new ArrayList<>();
+ private final List> activationCheckers = new ArrayList<>();
+
+ // ── Chained Abilities ──────────────────────────────────────────────────
+ private final Map chainedAbilities = new LinkedHashMap<>(); // name → ChainedAbility
+ private final Map chainedAbilitiesById = new LinkedHashMap<>(); // UUID → ChainedAbility
+ private int chainedAbilityRevision = 0;
+
+ // ── Category Managers ─────────────────────────────────────────────────
+ public final CategoryManager customAbilityCategories = new CategoryManager();
+ public final CategoryManager chainedAbilityCategories = new CategoryManager();
+ private final Map customAbilityCatMap = new HashMap<>(); // abilityName → catId
+ private final Map chainedAbilityCatMap = new HashMap<>(); // chainName → catId
+
+ // ── Effect Action Registry ──────────────────────────────────────────────
+ private final Map effectActions = new LinkedHashMap<>();
+
+ // ── Derived State ────────────────────────────────────────────────────────
+ private final Set builtInTypeIds = new HashSet<>();
+
+ public AbilityController() {
+ registerBuiltinTypes();
+ registerBuiltinConditionTypes();
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // TYPE REGISTRATION
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ public void registerType(Supplier factory) {
+ Ability temp = factory.get();
+ String typeId = temp.getTypeId();
+ if (abilityTypes.containsKey(typeId)) {
+ LogWriter.info("AbilityController: Overwriting type: " + typeId);
+ }
+ abilityTypes.put(typeId, factory);
+ if (temp.isBuiltIn()) {
+ builtInTypeIds.add(typeId);
+ }
+ }
+
+ public Ability create(String typeId) {
+ Supplier factory = abilityTypes.get(typeId);
+ return factory != null ? factory.get() : null;
+ }
+
+ public Ability fromNBT(NBTTagCompound nbt) {
+ if (nbt == null || !nbt.hasKey("typeId")) {
+ return null;
+ }
+
+ String typeId = nbt.getString("typeId");
+ Supplier factory = abilityTypes.get(typeId);
+ if (factory == null) {
+ LogWriter.info("AbilityController: Unknown ability type: " + typeId);
+ return null;
+ }
+
+ Ability ability = factory.get();
+ ability.readNBT(nbt);
+ return ability;
+ }
+
+ private void registerBuiltinTypes() {
+ registerType(CustomAbility::new);
+
+ registerType(AbilitySlam::new);
+ registerType(AbilityCharge::new);
+
+ registerType(AbilityHeavyHit::new);
+ registerType(AbilityCutter::new);
+
+ registerType(AbilitySweeper::new);
+ registerType(AbilityOrb::new);
+ registerType(AbilityDisc::new);
+ registerType(AbilityLaser::new);
+ registerType(AbilityBeam::new);
+
+ registerType(AbilityDash::new);
+ registerType(AbilityTeleport::new);
+
+ registerType(AbilityVortex::new);
+ registerType(AbilityShockwave::new);
+
+ registerType(AbilityGuard::new);
+ registerType(AbilityCounter::new);
+ registerType(AbilityDodge::new);
+ registerType(AbilityEffect::new);
+
+ registerType(AbilityHazard::new);
+ registerType(AbilityTrap::new);
+
+ registerType(AbilityDome::new);
+ registerType(AbilityWall::new);
+ registerType(AbilityShield::new);
+ }
+
+ private void registerBuiltinConditionTypes() {
+ registerCondition(ConditionHPThreshold::new);
+ registerCondition(ConditionHitCount::new);
+ registerCondition(ConditionItem::new);
+ registerCondition(ConditionQuestCompleted::new);
+ registerCondition(ConditionHasEffect::new);
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // BUILT-IN ABILITIES
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ public void registerAbility(String name, Ability ability) {
+ if (builtAbilities.containsKey(name)) {
+ LogWriter.info("AbilityController: Overwriting built-in ability: " + name);
+ }
+ if (!ability.isBuiltIn()) {
+ ability.setName(name);
+ }
+ builtAbilities.put(name, ability);
+ LogWriter.info("Registered ability: " + name);
+ }
+
+ public Ability getAbility(String name) {
+ return builtAbilities.get(name);
+ }
+
+ public Ability getAbilityByDisplayName(String displayName) {
+ for (Ability ability : builtAbilities.values()) {
+ if (ability.getDisplayName().equals(displayName)) {
+ return ability;
+ }
+ }
+ return null;
+ }
+
+ public Set getAbilityNames() {
+ return new LinkedHashSet<>(builtAbilities.keySet());
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // CUSTOM ABILITIES
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ // Incremented on any custom ability change; used by AbilitySlot for cache invalidation
+ private int customAbilityRevision = 0;
+
+ public void load() {
+ customAbilities.clear();
+ customAbilitiesById.clear();
+ abilityScriptHandlers.clear();
+ customAbilityCatMap.clear();
+
+ File dir = getDir();
+ customAbilityCategories.loadCategories(dir, "chained");
+
+ // Load from root directory (Uncategorized)
+ loadAbilitiesFromDir(dir, CategoryManager.UNCATEGORIZED_ID);
+
+ // Load from category subdirectories
+ for (Map.Entry entry : customAbilityCategories.getCategories().entrySet()) {
+ File catDir = new File(dir, entry.getValue().title);
+ loadAbilitiesFromDir(catDir, entry.getKey());
+ }
+
+ customAbilityRevision++;
+ LogWriter.info("Loaded " + customAbilities.size() + " custom abilities");
+
+ loadChainedAbilities();
+ }
+
+ private void loadAbilitiesFromDir(File dir, int catId) {
+ File[] files = dir.exists() ? dir.listFiles() : null;
+ if (files == null) return;
+ for (File file : files) {
+ if (!file.isFile() || !file.getName().endsWith(".json")) continue;
+ try {
+ String filename = file.getName();
+ String fileKey = filename.substring(0, filename.length() - 5);
+
+ NBTTagCompound nbt = NBTJsonUtil.LoadFile(file);
+ Ability ability = fromNBT(nbt);
+ if (ability == null) continue;
+
+ String name = FileNameHelper.sanitizeName(fileKey, "Ability");
+ name = makeUniqueNameForLoad(customAbilities, dir, file, name, fileKey);
+
+ boolean dirty = false;
+ if (!name.equals(fileKey)) {
+ File renamedFile = new File(dir, name + ".json");
+ if (file.renameTo(renamedFile)) {
+ file = renamedFile;
+ dirty = true;
+ }
+ }
+
+ ability.setName(name);
+
+ String uuid = ability.getId();
+ if (uuid == null || uuid.isEmpty()) {
+ uuid = UUID.randomUUID().toString();
+ ability.setId(uuid);
+ dirty = true;
+ }
+
+ if (dirty) {
+ NBTJsonUtil.SaveFile(file, ability.writeNBT(true));
+ }
+
+ customAbilities.put(name, ability);
+ customAbilitiesById.put(uuid, ability);
+ if (catId > CategoryManager.UNCATEGORIZED_ID) {
+ customAbilityCatMap.put(name, catId);
+ }
+ } catch (Exception e) {
+ LogWriter.error("Error loading custom ability: " + file.getAbsolutePath(), e);
+ }
+ }
+ }
+
+ private boolean nameFileExists(File dir, String name, File ignoredFile) {
+ File existing = new File(dir, name + ".json");
+ if (!existing.exists()) return false;
+ return ignoredFile == null || !existing.getAbsolutePath().equals(ignoredFile.getAbsolutePath());
+ }
+
+ private String makeUniqueNameForLoad(Map loadedMap, File dir, File currentFile, String baseName, String selfKey) {
+ String candidate = baseName;
+ while ((loadedMap.containsKey(candidate) && !candidate.equals(selfKey))
+ || nameFileExists(dir, candidate, currentFile)) {
+ candidate = candidate + "_";
+ }
+ return candidate;
+ }
+
+ private String makeUniqueNameForMap(Map map, String baseName, String selfName) {
+ String candidate = baseName;
+ while (map.containsKey(candidate) && (selfName == null || !candidate.equals(selfName))) {
+ candidate = candidate + "_";
+ }
+ return candidate;
+ }
+
+ public boolean saveCustomAbility(Ability ability) {
+ if (ability == null) return false;
+ if (ability.isBuiltIn()) return false;
+
+ String name = FileNameHelper.sanitizeName(ability.getName(), "Ability");
+ ability.setName(name);
+
+ String uuid = ability.getId();
+ boolean isNew = (uuid == null || uuid.isEmpty());
+ int catId = CategoryManager.UNCATEGORIZED_ID;
+
+ if (isNew) {
+ // Generate UUID for new ability
+ uuid = UUID.randomUUID().toString();
+ ability.setId(uuid);
+
+ // Ensure unique name
+ name = makeUniqueNameForMap(customAbilities, name, null);
+ ability.setName(name);
+ } else {
+ // Existing ability — check for rename via UUID lookup
+ Ability existing = customAbilitiesById.get(uuid);
+ if (existing != null) {
+ String oldName = existing.getName();
+ catId = customAbilityCatMap.getOrDefault(oldName, CategoryManager.UNCATEGORIZED_ID);
+ name = makeUniqueNameForMap(customAbilities, name, oldName);
+ ability.setName(name);
+
+ if (!oldName.equals(name)) {
+ // Delete old file and remove old map entry
+ File oldDir = getCustomAbilityDir(oldName);
+ File oldFile = new File(oldDir, oldName + ".json");
+ if (oldFile.exists()) {
+ oldFile.delete();
+ }
+ customAbilities.remove(oldName);
+ // Update catMap key
+ customAbilityCatMap.remove(oldName);
+ if (catId > CategoryManager.UNCATEGORIZED_ID) {
+ customAbilityCatMap.put(name, catId);
+ }
+ }
+ } else {
+ name = makeUniqueNameForMap(customAbilities, name, null);
+ ability.setName(name);
+ }
+ }
+
+ TagController.validateTagUUIDs(ability.getTagUUIDs());
+
+ File dir = getCustomAbilityDir(name);
+ File fileNew = new File(dir, name + ".json_new");
+ File fileCurrent = new File(dir, name + ".json");
+
+ try {
+ NBTTagCompound nbt = ability.writeNBT(true);
+
+ NBTJsonUtil.SaveFile(fileNew, nbt);
+
+ if (fileCurrent.exists()) {
+ fileCurrent.delete();
+ }
+ fileNew.renameTo(fileCurrent);
+ if (fileNew.exists()) {
+ fileNew.delete();
+ }
+
+ customAbilities.put(name, ability);
+ customAbilitiesById.put(uuid, ability);
+ customAbilityRevision++;
+ LogWriter.script("Saved custom ability: " + name + " [" + uuid + "]");
+ SyncController.syncAll(SyncType.CUSTOM_ABILITY);
+ return true;
+ } catch (Exception e) {
+ LogWriter.error("Error saving custom ability: " + name, e);
+ return false;
+ }
+ }
+
+ public Ability cloneCustomAbility(String originalName) {
+ Ability original = customAbilities.get(originalName);
+ if (original == null || original.isBuiltIn()) return null;
+
+ int originalCatId = customAbilityCatMap.getOrDefault(originalName, CategoryManager.UNCATEGORIZED_ID);
+
+ NBTTagCompound nbt = original.writeNBT(true);
+ nbt.setString("id", UUID.randomUUID().toString());
+
+ Ability clone = fromNBT(nbt);
+ if (clone == null) return null;
+
+ String name = clone.getName();
+ while (customAbilities.containsKey(name)) name += "_";
+ clone.setName(name);
+
+ saveCustomAbility(clone);
+
+ if (originalCatId > CategoryManager.UNCATEGORIZED_ID) {
+ customAbilityCatMap.put(clone.getName(), originalCatId);
+ }
+
+ return clone;
+ }
+
+ public boolean deleteCustomAbility(String name) {
+ if (name == null || name.isEmpty()) return false;
+
+ Ability removed = customAbilities.remove(name);
+ if (removed == null) {
+ String sanitized = FileNameHelper.sanitizeTextInput(name);
+ if (!sanitized.equals(name)) {
+ removed = customAbilities.remove(sanitized);
+ if (removed != null) {
+ name = sanitized;
+ }
+ }
+ }
+ if (removed == null) return false;
+
+ // Also remove from UUID index and script handler
+ String uuid = removed.getId();
+ if (uuid != null && !uuid.isEmpty()) {
+ customAbilitiesById.remove(uuid);
+ abilityScriptHandlers.remove(uuid);
+ }
+
+ File dir = getCustomAbilityDir(name);
+ File file = new File(dir, name + ".json");
+ if (file.exists()) {
+ file.delete();
+ }
+ customAbilityCatMap.remove(name);
+
+ // Clean up online players' unlocked ability lists
+ if (PlayerDataController.Instance != null) {
+ List snapshot = new ArrayList<>(PlayerDataController.Instance.getAllPlayerData());
+ for (PlayerData pData : snapshot) {
+ if (pData.abilityData != null) {
+ boolean changed = false;
+ if (uuid != null && !uuid.isEmpty() && pData.abilityData.hasUnlockedAbility(uuid)) {
+ pData.abilityData.lockAbility(uuid);
+ changed = true;
+ }
+ if (pData.abilityData.hasUnlockedAbility(name)) {
+ pData.abilityData.lockAbility(name);
+ changed = true;
+ }
+
+ // An active toggle holds the resolved Ability directly and keeps ticking it,
+ // so drop it without firing onToggle against an unregistered ability.
+ 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.syncAll(SyncType.CUSTOM_ABILITY);
+ return true;
+ }
+
+ public Ability getCustomAbility(String name) {
+ Ability ability = customAbilities.get(name);
+ if (ability != null) return ability;
+ String sanitized = FileNameHelper.sanitizeTextInput(name);
+ if (!sanitized.equals(name)) {
+ return customAbilities.get(sanitized);
+ }
+ return null;
+ }
+
+ public Set getCustomAbilityNames() {
+ return new LinkedHashSet<>(customAbilities.keySet());
+ }
+
+ public Map getCustomAbilities() {
+ return customAbilities;
+ }
+
+ public synchronized void setCustomAbilities(Map synced) {
+ customAbilities.clear();
+ customAbilitiesById.clear();
+ customAbilities.putAll(synced);
+ for (Ability ability : synced.values()) {
+ String uuid = ability.getId();
+ if (uuid != null && !uuid.isEmpty()) {
+ customAbilitiesById.put(uuid, ability);
+ }
+ }
+ customAbilityRevision++;
+ }
+
+ public int getCustomAbilityRevision() {
+ return customAbilityRevision;
+ }
+
+ private File getDir() {
+ File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities");
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ return dir;
+ }
+
+ private File getCustomAbilityDir(String name) {
+ int catId = customAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID);
+ return customAbilityCategories.getCategoryDir(catId);
+ }
+
+ private File getChainedAbilityDir(String name) {
+ int catId = chainedAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID);
+ return chainedAbilityCategories.getCategoryDir(catId);
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // CUSTOM ABILITY CATEGORY HELPERS
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ public Map getCustomAbilityCategoryScrollData() {
+ return customAbilityCategories.getCategoryScrollData();
+ }
+
+ public Map getCustomAbilityItemsByCategoryScrollData(int catId) {
+ Map map = new HashMap<>();
+ for (Map.Entry entry : customAbilities.entrySet()) {
+ int assignedCat = customAbilityCatMap.getOrDefault(entry.getKey(), CategoryManager.UNCATEGORIZED_ID);
+ if (assignedCat == catId) {
+ map.put(entry.getKey(), entry.getValue().getAllowedBy().ordinal());
+ }
+ }
+ return map;
+ }
+
+ public HashMap> getCustomAbilityTagMapForCategory(int catId) {
+ HashMap> tagMap = new HashMap<>();
+ for (Map.Entry entry : customAbilities.entrySet()) {
+ int assignedCat = customAbilityCatMap.getOrDefault(entry.getKey(), CategoryManager.UNCATEGORIZED_ID);
+ if (assignedCat == catId && !entry.getValue().getTagUUIDs().isEmpty()) {
+ tagMap.put(entry.getKey(), entry.getValue().getTagUUIDs());
+ }
+ }
+ return tagMap;
+ }
+
+ public void moveCustomAbilityToCategory(String name, int destCatId) {
+ Ability ability = customAbilities.get(name);
+ if (ability == null) return;
+
+ int oldCatId = customAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID);
+ if (oldCatId == destCatId) return;
+
+ File oldDir = customAbilityCategories.getCategoryDir(oldCatId);
+ File newDir = customAbilityCategories.getCategoryDir(destCatId);
+ if (!newDir.exists()) newDir.mkdirs();
+
+ File oldFile = new File(oldDir, name + ".json");
+ File newFile = new File(newDir, name + ".json");
+ if (oldFile.exists()) oldFile.renameTo(newFile);
+
+ if (destCatId == CategoryManager.UNCATEGORIZED_ID) {
+ customAbilityCatMap.remove(name);
+ } else {
+ customAbilityCatMap.put(name, destCatId);
+ }
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // CHAINED ABILITY CATEGORY HELPERS
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ public Map getChainedAbilityCategoryScrollData() {
+ return chainedAbilityCategories.getCategoryScrollData();
+ }
+
+ public Map getChainedAbilityItemsByCategoryScrollData(int catId) {
+ Map map = new HashMap<>();
+ for (Map.Entry entry : chainedAbilities.entrySet()) {
+ int assignedCat = chainedAbilityCatMap.getOrDefault(entry.getKey(), CategoryManager.UNCATEGORIZED_ID);
+ if (assignedCat == catId) {
+ map.put(entry.getKey(), entry.getValue().getAllowedBy().ordinal());
+ }
+ }
+ return map;
+ }
+
+ public void moveChainedAbilityToCategory(String name, int destCatId) {
+ ChainedAbility chain = chainedAbilities.get(name);
+ if (chain == null) return;
+
+ int oldCatId = chainedAbilityCatMap.getOrDefault(name, CategoryManager.UNCATEGORIZED_ID);
+ if (oldCatId == destCatId) return;
+
+ File oldDir = chainedAbilityCategories.getCategoryDir(oldCatId);
+ File newDir = chainedAbilityCategories.getCategoryDir(destCatId);
+ if (!newDir.exists()) newDir.mkdirs();
+
+ File oldFile = new File(oldDir, name + ".json");
+ File newFile = new File(newDir, name + ".json");
+ if (oldFile.exists()) oldFile.renameTo(newFile);
+
+ if (destCatId == CategoryManager.UNCATEGORIZED_ID) {
+ chainedAbilityCatMap.remove(name);
+ } else {
+ chainedAbilityCatMap.put(name, destCatId);
+ }
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // CHAINED ABILITIES
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ private void loadChainedAbilities() {
+ chainedAbilities.clear();
+ chainedAbilitiesById.clear();
+ chainedAbilityScriptHandlers.clear();
+ chainedAbilityCatMap.clear();
+
+ File dir = getChainedDir();
+ chainedAbilityCategories.loadCategories(dir);
+
+ // Load from root directory (Uncategorized)
+ loadChainedFromDir(dir, CategoryManager.UNCATEGORIZED_ID);
+
+ // Load from category subdirectories
+ for (Map.Entry entry : chainedAbilityCategories.getCategories().entrySet()) {
+ File catDir = new File(dir, entry.getValue().title);
+ loadChainedFromDir(catDir, entry.getKey());
+ }
+
+ chainedAbilityRevision++;
+ LogWriter.info("Loaded " + chainedAbilities.size() + " chained abilities");
+ }
+
+ private void loadChainedFromDir(File dir, int catId) {
+ File[] files = dir.exists() ? dir.listFiles() : null;
+ if (files == null) return;
+ for (File file : files) {
+ if (!file.isFile() || !file.getName().endsWith(".json")) continue;
+ try {
+ String filename = file.getName();
+ String fileKey = filename.substring(0, filename.length() - 5);
+
+ NBTTagCompound nbt = NBTJsonUtil.LoadFile(file);
+ ChainedAbility chain = new ChainedAbility();
+ chain.readNBT(nbt);
+
+ String name = FileNameHelper.sanitizeName(fileKey, "Chain");
+ name = makeUniqueNameForLoad(chainedAbilities, dir, file, name, fileKey);
+
+ boolean dirty = false;
+ if (!name.equals(fileKey)) {
+ File renamedFile = new File(dir, name + ".json");
+ if (file.renameTo(renamedFile)) {
+ file = renamedFile;
+ dirty = true;
+ }
+ }
+
+ chain.setName(name);
+
+ String uuid = chain.getId();
+ if (uuid == null || uuid.isEmpty()) {
+ uuid = UUID.randomUUID().toString();
+ chain.setId(uuid);
+ dirty = true;
+ }
+
+ if (dirty) {
+ NBTJsonUtil.SaveFile(file, chain.writeNBT(true));
+ }
+
+ chainedAbilities.put(name, chain);
+ chainedAbilitiesById.put(uuid, chain);
+ if (catId > CategoryManager.UNCATEGORIZED_ID) {
+ chainedAbilityCatMap.put(name, catId);
+ }
+ } catch (Exception e) {
+ LogWriter.error("Error loading chained ability: " + file.getAbsolutePath(), e);
+ }
+ }
+ }
+
+ public boolean saveChainedAbility(ChainedAbility chain) {
+ if (chain == null) return false;
+
+ String name = FileNameHelper.sanitizeName(chain.getName(), "Chain");
+ chain.setName(name);
+
+ String uuid = chain.getId();
+ boolean isNew = (uuid == null || uuid.isEmpty());
+
+ if (isNew) {
+ uuid = UUID.randomUUID().toString();
+ chain.setId(uuid);
+
+ name = makeUniqueNameForMap(chainedAbilities, name, null);
+ chain.setName(name);
+ } else {
+ ChainedAbility existing = chainedAbilitiesById.get(uuid);
+ if (existing != null) {
+ String oldName = existing.getName();
+ int catId = chainedAbilityCatMap.getOrDefault(oldName, CategoryManager.UNCATEGORIZED_ID);
+ name = makeUniqueNameForMap(chainedAbilities, name, oldName);
+ chain.setName(name);
+
+ if (!oldName.equals(name)) {
+ File oldDir = getChainedAbilityDir(oldName);
+ File oldFile = new File(oldDir, oldName + ".json");
+ if (oldFile.exists()) {
+ oldFile.delete();
+ }
+ chainedAbilities.remove(oldName);
+ chainedAbilityCatMap.remove(oldName);
+ if (catId > CategoryManager.UNCATEGORIZED_ID) {
+ chainedAbilityCatMap.put(name, catId);
+ }
+ }
+ } else {
+ name = makeUniqueNameForMap(chainedAbilities, name, null);
+ chain.setName(name);
+ }
+ }
+
+ File dir = getChainedAbilityDir(name);
+ File fileNew = new File(dir, name + ".json_new");
+ File fileCurrent = new File(dir, name + ".json");
+
+ try {
+ NBTTagCompound nbt = chain.writeNBT(true);
+
+ NBTJsonUtil.SaveFile(fileNew, nbt);
+
+ if (fileCurrent.exists()) {
+ fileCurrent.delete();
+ }
+ fileNew.renameTo(fileCurrent);
+ if (fileNew.exists()) {
+ fileNew.delete();
+ }
+
+ chainedAbilities.put(name, chain);
+ chainedAbilitiesById.put(uuid, chain);
+ chainedAbilityRevision++;
+ LogWriter.script("Saved chained ability: " + name + " [" + uuid + "]");
+ SyncController.syncAll(SyncType.CHAINED_ABILITY);
+ return true;
+ } catch (Exception e) {
+ LogWriter.error("Error saving chained ability: " + name, e);
+ return false;
+ }
+ }
+
+ public ChainedAbility cloneChainedAbility(String originalName) {
+ ChainedAbility original = chainedAbilities.get(originalName);
+ if (original == null) return null;
+
+ int originalCatId = chainedAbilityCatMap.getOrDefault(originalName, CategoryManager.UNCATEGORIZED_ID);
+
+ NBTTagCompound nbt = original.writeNBT(true);
+ nbt.setString("Id", UUID.randomUUID().toString());
+
+ ChainedAbility clone = new ChainedAbility();
+ clone.readNBT(nbt);
+
+ String name = clone.getName();
+ while (chainedAbilities.containsKey(name)) name += "_";
+ clone.setName(name);
+
+ saveChainedAbility(clone);
+
+ if (originalCatId > CategoryManager.UNCATEGORIZED_ID) {
+ chainedAbilityCatMap.put(clone.getName(), originalCatId);
+ }
+
+ return clone;
+ }
+
+ public boolean deleteChainedAbility(String name) {
+ if (name == null || name.isEmpty()) return false;
+
+ ChainedAbility removed = chainedAbilities.remove(name);
+ if (removed == null) {
+ String sanitized = FileNameHelper.sanitizeTextInput(name);
+ if (!sanitized.equals(name)) {
+ removed = chainedAbilities.remove(sanitized);
+ if (removed != null) {
+ name = sanitized;
+ }
+ }
+ }
+ if (removed == null) return false;
+
+ String uuid = removed.getId();
+ if (uuid != null && !uuid.isEmpty()) {
+ chainedAbilitiesById.remove(uuid);
+ chainedAbilityScriptHandlers.remove(uuid);
+ }
+
+ File dir = getChainedAbilityDir(name);
+ File file = new File(dir, name + ".json");
+ if (file.exists()) {
+ file.delete();
+ }
+ chainedAbilityCatMap.remove(name);
+
+ // Clean up online players' unlocked ability lists (chain keys use "chain:" prefix)
+ if (PlayerDataController.Instance != null) {
+ List snapshot = new ArrayList<>(PlayerDataController.Instance.getAllPlayerData());
+ for (PlayerData pData : snapshot) {
+ if (pData.abilityData != null) {
+ String chainKey = "chain:" + (uuid != null && !uuid.isEmpty() ? uuid : name);
+ if (pData.abilityData.hasUnlockedAbility(chainKey)) {
+ pData.abilityData.lockAbility(chainKey);
+ }
+ String chainNameKey = "chain:" + name;
+ if (!chainNameKey.equals(chainKey) && pData.abilityData.hasUnlockedAbility(chainNameKey)) {
+ pData.abilityData.lockAbility(chainNameKey);
+ }
+ }
+ }
+ }
+
+ chainedAbilityRevision++;
+ LogWriter.script("Deleted chained ability: " + name);
+ SyncController.syncAll(SyncType.CHAINED_ABILITY);
+ return true;
+ }
+
+ public ChainedAbility resolveChainedAbility(String key) {
+ if (key == null || key.isEmpty()) return null;
+
+ ChainedAbility byId = chainedAbilitiesById.get(key);
+ if (byId != null) return byId.deepCopy();
+
+ ChainedAbility chain = chainedAbilities.get(key);
+ if (chain != null) return chain.deepCopy();
+
+ for (Map.Entry entry : chainedAbilities.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(key)) {
+ return entry.getValue().deepCopy();
+ }
+ }
+
+ String sanitizedKey = FileNameHelper.sanitizeTextInput(key);
+ if (!sanitizedKey.equals(key)) {
+ ChainedAbility sanitized = chainedAbilities.get(sanitizedKey);
+ if (sanitized != null) return sanitized.deepCopy();
+ }
+
+ return null;
+ }
+
+ /**
+ * Resolve a chained ability by key and return the live (non-copied) reference.
+ * For validation/permission checks only — do NOT expose or modify the returned chain.
+ * Uses the same lookup chain as {@link #resolveChainedAbility(String)}.
+ */
+ public ChainedAbility peekChainedAbility(String key) {
+ if (key == null || key.isEmpty()) return null;
+
+ ChainedAbility byId = chainedAbilitiesById.get(key);
+ if (byId != null) return byId;
+
+ ChainedAbility chain = chainedAbilities.get(key);
+ if (chain != null) return chain;
+
+ for (Map.Entry entry : chainedAbilities.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(key)) {
+ return entry.getValue();
+ }
+ }
+
+ String sanitizedKey = FileNameHelper.sanitizeTextInput(key);
+ if (!sanitizedKey.equals(key)) {
+ ChainedAbility sanitized = chainedAbilities.get(sanitizedKey);
+ if (sanitized != null) return sanitized;
+ }
+
+ return null;
+ }
+
+ public boolean canResolveChainedAbility(String key) {
+ if (key == null || key.isEmpty()) return false;
+ if (chainedAbilitiesById.containsKey(key)) return true;
+ if (chainedAbilities.containsKey(key)) return true;
+ for (String name : chainedAbilities.keySet()) {
+ if (name.equalsIgnoreCase(key)) return true;
+ }
+ String sanitizedKey = FileNameHelper.sanitizeTextInput(key);
+ if (!sanitizedKey.equals(key) && chainedAbilities.containsKey(sanitizedKey)) return true;
+ return false;
+ }
+
+ @Override
+ public ChainedAbility getChainedAbility(String name) {
+ ChainedAbility chain = chainedAbilities.get(name);
+ if (chain == null) {
+ String sanitized = FileNameHelper.sanitizeTextInput(name);
+ if (!sanitized.equals(name)) {
+ chain = chainedAbilities.get(sanitized);
+ }
+ }
+ return chain != null ? chain.deepCopy() : null;
+ }
+
+ public ChainedAbility getChainedAbilityByUUID(String uuid) {
+ return chainedAbilitiesById.get(uuid);
+ }
+
+ public Set getChainedAbilityNamesSet() {
+ return new LinkedHashSet<>(chainedAbilities.keySet());
+ }
+
+ public Map getChainedAbilities() {
+ return chainedAbilities;
+ }
+
+ @Override
+ public String[] getChainedAbilityNames() {
+ return chainedAbilities.keySet().toArray(new String[0]);
+ }
+
+ @Override
+ public boolean hasChainedAbilityName(String name) {
+ if (chainedAbilities.containsKey(name)) return true;
+ String sanitized = FileNameHelper.sanitizeTextInput(name);
+ return !sanitized.equals(name) && chainedAbilities.containsKey(sanitized);
+ }
+
+ @Override
+ public boolean deleteChainedAbilityByName(String name) {
+ return deleteChainedAbility(name);
+ }
+
+ @Override
+ public boolean saveChainedAbility(IChainedAbility chain) {
+ if (chain instanceof ChainedAbility) {
+ return saveChainedAbility((ChainedAbility) chain);
+ }
+ return false;
+ }
+
+ public int getChainedAbilityRevision() {
+ return chainedAbilityRevision;
+ }
+
+ public synchronized void setChainedAbilities(Map synced) {
+ chainedAbilities.clear();
+ chainedAbilitiesById.clear();
+ chainedAbilities.putAll(synced);
+ for (ChainedAbility chain : synced.values()) {
+ String uuid = chain.getId();
+ if (uuid != null && !uuid.isEmpty()) {
+ chainedAbilitiesById.put(uuid, chain);
+ }
+ }
+ chainedAbilityRevision++;
+ }
+
+ private File getChainedDir() {
+ File dir = new File(CustomNpcs.getWorldSaveDirectory(), "abilities" + File.separator + "chained");
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ return dir;
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // RESOLUTION
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ public Ability resolveAbility(String key) {
+ if (key == null || key.isEmpty()) return null;
+
+ // Custom: UUID lookup (most common for persistent references)
+ Ability byUuid = customAbilitiesById.get(key);
+ if (byUuid != null) return byUuid.deepCopy();
+
+ // Built-in: exact key
+ Ability builtIn = builtAbilities.get(key);
+ if (builtIn != null) return builtIn.deepCopy();
+
+ // Built-in: case-insensitive key
+ String lowerKey = key.toLowerCase();
+ for (Map.Entry entry : builtAbilities.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(lowerKey)) {
+ return entry.getValue().deepCopy();
+ }
+ }
+
+ // Built-in: by ID (case-insensitive)
+ for (Ability ability : builtAbilities.values()) {
+ if (key.equalsIgnoreCase(ability.getId())) {
+ return ability.deepCopy();
+ }
+ }
+
+ // Custom: exact name
+ Ability custom = customAbilities.get(key);
+ if (custom != null) return custom.deepCopy();
+
+ // Custom: case-insensitive name
+ for (Map.Entry entry : customAbilities.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(key)) {
+ return entry.getValue().deepCopy();
+ }
+ }
+
+ return null;
+ }
+
+ public Set getAbilityKeys() {
+ Set keys = new LinkedHashSet<>();
+ for (Ability ability : builtAbilities.values()) {
+ String id = ability.getId();
+ if (id != null && !id.isEmpty()) {
+ keys.add(id);
+ }
+ }
+ // Custom abilities keyed by UUID (stable references)
+ for (Ability ability : customAbilities.values()) {
+ String id = ability.getId();
+ if (id != null && !id.isEmpty()) {
+ keys.add(id);
+ }
+ }
+ return keys;
+ }
+
+ public Set getPlayerAbilityKeys() {
+ Set keys = new LinkedHashSet<>();
+ for (Ability ability : builtAbilities.values()) {
+ if (ability.getAllowedBy().allowsPlayer()) {
+ String id = ability.getId();
+ if (id != null && !id.isEmpty()) {
+ keys.add(id);
+ }
+ }
+ }
+ // Custom abilities keyed by UUID (stable references)
+ for (Ability ability : customAbilities.values()) {
+ if (ability.getAllowedBy().allowsPlayer()) {
+ String id = ability.getId();
+ if (id != null && !id.isEmpty()) {
+ keys.add(id);
+ }
+ }
+ }
+ return keys;
+ }
+
+ public boolean hasAbility(String key) {
+ return builtAbilities.containsKey(key) || customAbilities.containsKey(key)
+ || customAbilitiesById.containsKey(key);
+ }
+
+ public Ability getCustomAbilityByUUID(String uuid) {
+ return customAbilitiesById.get(uuid);
+ }
+
+ public Ability getCustomAbilityByName(String name) {
+ return customAbilities.get(name);
+ }
+
+ /**
+ * Resolve an ability by key and return the live (non-copied) reference.
+ * For validation/permission checks only — do NOT expose or modify the returned ability.
+ * Uses the same lookup chain as {@link #resolveAbility(String)}.
+ */
+ public Ability peekAbility(String key) {
+ if (key == null || key.isEmpty()) return null;
+
+ // Custom: UUID lookup
+ Ability byUuid = customAbilitiesById.get(key);
+ if (byUuid != null) return byUuid;
+
+ // Built-in: exact key
+ Ability builtIn = builtAbilities.get(key);
+ if (builtIn != null) return builtIn;
+
+ // Built-in: case-insensitive key
+ for (Map.Entry entry : builtAbilities.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(key)) {
+ return entry.getValue();
+ }
+ }
+
+ // Built-in: by ID (case-insensitive)
+ for (Ability ability : builtAbilities.values()) {
+ if (key.equalsIgnoreCase(ability.getId())) return ability;
+ }
+
+ // Custom: exact name
+ Ability custom = customAbilities.get(key);
+ if (custom != null) return custom;
+
+ // Custom: case-insensitive name
+ for (Map.Entry entry : customAbilities.entrySet()) {
+ if (entry.getKey().equalsIgnoreCase(key)) {
+ return entry.getValue();
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Check if a key can be resolved to a valid ability without creating a deep copy.
+ * Uses the same lookup chain as {@link #resolveAbility(String)}.
+ */
+ public boolean canResolveAbility(String key) {
+ if (key == null || key.isEmpty()) return false;
+
+ // Custom: UUID lookup
+ if (customAbilitiesById.containsKey(key)) return true;
+
+ // Built-in: exact key
+ if (builtAbilities.containsKey(key)) return true;
+
+ // Built-in: by ID
+ for (Ability ability : builtAbilities.values()) {
+ if (key.equals(ability.getId())) return true;
+ }
+
+ // Custom: exact name
+ if (customAbilities.containsKey(key)) return true;
+
+ return false;
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // UNIFIED ACTION RESOLUTION
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ /**
+ * Resolve any action key to an IAbilityAction.
+ * Checks abilities first, then chained abilities.
+ */
+ public IAbilityAction resolveAction(String key) {
+ if (key == null || key.isEmpty()) return null;
+
+ Ability ability = resolveAbility(key);
+ if (ability != null) return ability;
+
+ return resolveChainedAbility(key);
+ }
+
+ /**
+ * Check if a key can be resolved as any action (ability or chain).
+ */
+ public boolean canResolveAction(String key) {
+ if (canResolveAbility(key)) return true;
+ return canResolveChainedAbility(key);
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // EXTENSION POINTS
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ public void registerVariant(String typeId, AbilityVariant variant) {
+ externalVariants.computeIfAbsent(typeId, k -> new ArrayList<>()).add(variant);
+ }
+
+ public List getVariantsForType(String typeId) {
+ List result = new ArrayList<>();
+ Ability temp = create(typeId);
+ if (temp != null) {
+ result.addAll(temp.getVariants());
+ }
+ List ext = externalVariants.get(typeId);
+ if (ext != null) {
+ // If no built-in variants exist but external ones do,
+ // inject a "Base" variant so the user always gets a choice
+ if (result.isEmpty()) {
+ result.add(new AbilityVariant("ability.variant.base", a -> {
+ }));
+ }
+ result.addAll(ext);
+ }
+ return result;
+ }
+
+ public void registerFieldProvider(IAbilityFieldProvider provider) {
+ fieldProviders.add(provider);
+ }
+
+ public List getFieldProviders() {
+ return fieldProviders;
+ }
+
+ public void registerChainedFieldProvider(IChainedAbilityFieldProvider provider) {
+ chainedFieldProviders.add(provider);
+ }
+
+ public List getChainedFieldProviders() {
+ return chainedFieldProviders;
+ }
+
+ public void registerExtender(IAbilityExtender extender) {
+ extenders.add(extender);
+ }
+
+ public List getExtenders() {
+ return extenders;
+ }
+
+ public void registerCondition(Supplier conditionFactory) {
+ AbilityCondition temp = conditionFactory.get();
+ String typeId = temp.getTypeId();
+ if (conditionTypes.containsKey(typeId)) {
+ LogWriter.info("AbilityController: Overwriting Condition type: " + typeId);
+ }
+ conditionTypes.put(typeId, conditionFactory);
+ }
+
+ public Supplier getConditionType(String key) {
+ return conditionTypes.get(key);
+ }
+
+ public String[] getConditionTypes() {
+ return conditionTypes.keySet().toArray(new String[0]);
+ }
+
+ public List getConditionNamespaces() {
+ LinkedHashSet seen = new LinkedHashSet<>();
+ for (String typeId : conditionTypes.keySet()) {
+ String[] parts = typeId.split("\\.", 3);
+ if (parts.length >= 2) {
+ seen.add(parts[1]);
+ }
+ }
+ return new ArrayList<>(seen);
+ }
+
+ public String[] getConditionTypesByNamespace(String namespace) {
+ String prefix = "condition." + namespace + ".";
+ List result = new ArrayList<>();
+ for (String typeId : conditionTypes.keySet()) {
+ if (typeId.startsWith(prefix)) {
+ result.add(typeId);
+ }
+ }
+ return result.toArray(new String[0]);
+ }
+
+ public void registerFlightChecker(Predicate checker) {
+ flightCheckers.add(checker);
+ }
+
+ public boolean isPlayerFlying(EntityPlayer player) {
+ if (player.capabilities.isFlying) return true;
+ for (Predicate checker : flightCheckers) {
+ if (checker.test(player)) return true;
+ }
+ return false;
+ }
+
+ public void registerActivationChecker(Predicate checker) {
+ activationCheckers.add(checker);
+ }
+
+ public boolean canPlayerActivate(EntityPlayer player) {
+ for (Predicate checker : activationCheckers) {
+ if (!checker.test(player)) return false;
+ }
+ return true;
+ }
+
+ /**
+ * Fire onAbilityStart on all extenders. Returns false if ANY extender cancels.
+ */
+ public boolean fireOnAbilityStart(Ability ability, EntityLivingBase caster, EntityLivingBase target) {
+ for (IAbilityExtender ext : extenders) {
+ if (!ext.onAbilityStart(ability, caster, target)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Fire onAbilityTick on all extenders. Returns false if ANY extender says to interrupt.
+ */
+ public boolean fireOnAbilityTick(Ability ability, EntityLivingBase caster, EntityLivingBase target,
+ AbilityPhase phase, int tick) {
+ for (IAbilityExtender ext : extenders) {
+ if (!ext.onAbilityTick(ability, caster, target, phase, tick)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Fire onAbilityComplete on all extenders.
+ */
+ public void fireOnAbilityComplete(Ability ability, EntityLivingBase caster, EntityLivingBase target,
+ boolean interrupted) {
+ for (IAbilityExtender ext : extenders) {
+ ext.onAbilityComplete(ability, caster, target, interrupted);
+ }
+ }
+
+ /**
+ * Fire onAbilityDamage on all extenders. Chain of responsibility — first true wins.
+ */
+ public boolean fireOnAbilityDamage(Ability ability, EntityLivingBase caster, EntityLivingBase target,
+ float damage, float knockback, float knockbackUp,
+ double knockbackDirX, double knockbackDirZ,
+ float damageMultiplier) {
+ for (IAbilityExtender ext : extenders) {
+ if (ext.onAbilityDamage(ability, caster, target, damage, knockback, knockbackUp,
+ knockbackDirX, knockbackDirZ, damageMultiplier)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Fire modifyProjectileDamage on all extenders. Cumulative — each extender's output feeds the next.
+ */
+ public float fireModifyProjectileDamage(Ability ability, EntityLivingBase caster, float baseDamage) {
+ float damage = baseDamage;
+ for (IAbilityExtender ext : extenders) {
+ damage = ext.modifyProjectileDamage(ability, caster, damage);
+ }
+ return damage;
+ }
+
+ /**
+ * Fire modifyBarrierHealth on all extenders. Cumulative — each extender's output feeds the next.
+ */
+ public float fireModifyBarrierHealth(Ability ability, EntityLivingBase caster, float baseHealth) {
+ float health = baseHealth;
+ for (IAbilityExtender ext : extenders) {
+ health = ext.modifyBarrierHealth(ability, caster, health);
+ }
+ 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.
+ */
+ public boolean fireOnAbilityHeal(Ability ability, EntityLivingBase caster, EntityLivingBase target, float healAmount) {
+ for (IAbilityExtender ext : extenders) {
+ if (ext.onAbilityHeal(ability, caster, target, healAmount)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public Boolean fireCheckConditions(AbilityCondition condition, EntityLivingBase caster, EntityLivingBase target) {
+ for (IAbilityExtender ext : extenders) {
+ Boolean result = ext.onCheckCondition(condition, caster, target);
+ if (result != null) {
+ return result;
+ }
+ }
+
+ return null;
+ }
+
+ public Boolean fireCheckConditionsForPlayer(AbilityCondition condition, EntityLivingBase player) {
+ for (IAbilityExtender ext : extenders) {
+ Boolean result = ext.onCheckConditionForPlayer(condition, player);
+ if (result != null) {
+ return result;
+ }
+ }
+ return null;
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // IAbilityHandler
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ @Override
+ public String[] getTypes() {
+ return abilityTypes.keySet().toArray(new String[0]);
+ }
+
+ public boolean isBuiltInType(String typeId) {
+ return builtInTypeIds.contains(typeId);
+ }
+
+ public boolean isConcurrentCapableType(String typeId) {
+ Supplier factory = abilityTypes.get(typeId);
+ if (factory == null) return false;
+ return factory.get().isConcurrentCapable();
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════════
+ // EFFECT ACTION REGISTRY
+ // ═══════════════════════════════════════════════════════════════════════════
+
+ public void registerEffectAction(IEffectAction action) {
+ if (action == null || action.getId() == null) return;
+ effectActions.put(action.getId(), action);
+ }
+
+ public IEffectAction getEffectAction(String id) {
+ return effectActions.get(id);
+ }
+
+ public String[] getEffectActionIds() {
+ return effectActions.keySet().toArray(new String[0]);
+ }
+
+ public java.util.Collection getEffectActions() {
+ return effectActions.values();
+ }
+
+ public boolean hasEffectActions() {
+ return !effectActions.isEmpty();
+ }
+
+ @Override
+ public boolean hasType(String typeId) {
+ return abilityTypes.containsKey(typeId);
+ }
+
+ public boolean isAllowedByPlayer(String typeId) {
+ if (abilityTypes.containsKey(typeId)) {
+ Ability temp = abilityTypes.get(typeId).get();
+ return temp.getAllowedBy().allowsPlayer();
+ }
+
+ return false;
+ }
+
+ public boolean isAllowedByNPC(String typeId) {
+ if (abilityTypes.containsKey(typeId)) {
+ Ability temp = abilityTypes.get(typeId).get();
+ return temp.getAllowedBy().allowsNpc();
+ }
+
+ return false;
+ }
+
+ public boolean isAllowedByBoth(String typeId) {
+ if (abilityTypes.containsKey(typeId)) {
+ Ability temp = abilityTypes.get(typeId).get();
+ return temp.getAllowedBy() == UserType.BOTH;
+ }
+
+ return false;
+ }
+
+ @Override
+ public String[] getAbilityNameArray() {
+ return builtAbilities.keySet().toArray(new String[0]);
+ }
+
+ @Override
+ public boolean hasAbilityName(String name) {
+ return builtAbilities.containsKey(name);
+ }
+
+ @Override
+ public String[] getCustomAbilityNameArray() {
+ return customAbilities.keySet().toArray(new String[0]);
+ }
+
+ @Override
+ public boolean hasCustomAbilityName(String name) {
+ if (customAbilities.containsKey(name)) return true;
+ String sanitized = FileNameHelper.sanitizeTextInput(name);
+ return !sanitized.equals(name) && customAbilities.containsKey(sanitized);
+ }
+
+ @Override
+ public boolean deleteCustomAbilityByName(String name) {
+ return deleteCustomAbility(name);
+ }
+
+}
diff --git a/src/main/java/kamkeel/npcs/controllers/EnergyController.java b/src/main/java/kamkeel/npcs/controllers/EnergyController.java
new file mode 100644
index 000000000..5b6bc123a
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/controllers/EnergyController.java
@@ -0,0 +1,209 @@
+package kamkeel.npcs.controllers;
+
+import kamkeel.npcs.controllers.data.energy.IEnergyExtender;
+import kamkeel.npcs.entity.*;
+import net.minecraft.entity.Entity;
+import net.minecraft.entity.EntityLivingBase;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.world.World;
+import noppes.npcs.api.IEnergyHandler;
+import noppes.npcs.api.IWorld;
+import noppes.npcs.api.entity.*;
+import noppes.npcs.api.entity.IEnergyExplosion;
+import noppes.npcs.scripted.NpcAPI;
+import noppes.npcs.scripted.entity.ScriptEnergyExplosion;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Central controller for script-created energy entities and handler registration.
+ * Provides factory methods for creating all energy entity types and routes
+ * damage through registered handlers when entities have customDamageData
+ * but no sourceAbility.
+ */
+public class EnergyController implements IEnergyHandler {
+
+ public static EnergyController Instance = new EnergyController();
+
+ private final List extenders = new ArrayList<>();
+
+ // ═══════════════════════════════════════════════════════════════════
+ // HANDLER REGISTRATION
+ // ═══════════════════════════════════════════════════════════════════
+
+ public void registerExtender(IEnergyExtender handler) {
+ extenders.add(handler);
+ }
+
+ public List getExtenders() {
+ return extenders;
+ }
+
+ // ═══════════════════════════════════════════════════════════════════
+ // DAMAGE ROUTING
+ // ═══════════════════════════════════════════════════════════════════
+
+ /**
+ * Fire onEnergyDamage on all handlers. Chain of responsibility — first true wins.
+ */
+ public boolean fireOnEnergyDamage(Entity energyEntity, EntityLivingBase owner,
+ EntityLivingBase target, float damage,
+ float knockback, float knockbackUp,
+ double kbDirX, double kbDirZ,
+ float damageMultiplier,
+ NBTTagCompound damageData) {
+ for (IEnergyExtender handler : extenders) {
+ if (handler.onEnergyDamage(energyEntity, owner, target, damage,
+ knockback, knockbackUp, kbDirX, kbDirZ, damageMultiplier, damageData)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Fire modifyEnergyDamage on all handlers. Cumulative — each handler's output feeds the next.
+ */
+ public float fireModifyEnergyDamage(Entity energyEntity, EntityLivingBase owner,
+ float baseDamage, NBTTagCompound damageData) {
+ float damage = baseDamage;
+ for (IEnergyExtender handler : extenders) {
+ damage = handler.modifyEnergyDamage(energyEntity, owner, damage, damageData);
+ }
+ return damage;
+ }
+
+ // ═══════════════════════════════════════════════════════════════════
+ // INTERNAL FACTORY METHODS (MC types)
+ // ═══════════════════════════════════════════════════════════════════
+
+ public EntityAbilityOrb createOrbInternal(World world, Entity owner, double x, double y, double z, float size) {
+ EntityAbilityOrb entity = new EntityAbilityOrb(world);
+ entity.setPosition(x, y, z);
+ entity.setStartPosition(x, y, z);
+ entity.setOwnerEntityId(owner.getEntityId());
+ entity.setProjectileSize(size);
+ return entity;
+ }
+
+ public EntityAbilityBeam createBeamInternal(World world, Entity owner, double x, double y, double z,
+ float beamWidth, float headSize) {
+ EntityAbilityBeam entity = new EntityAbilityBeam(world);
+ entity.setPosition(x, y, z);
+ entity.setStartPosition(x, y, z);
+ entity.setOwnerEntityId(owner.getEntityId());
+ entity.setBeamWidth(beamWidth);
+ entity.setHeadSize(headSize);
+ return entity;
+ }
+
+ public EntityAbilityDisc createDiscInternal(World world, Entity owner, double x, double y, double z,
+ float radius, float thickness) {
+ EntityAbilityDisc entity = new EntityAbilityDisc(world);
+ entity.setPosition(x, y, z);
+ entity.setStartPosition(x, y, z);
+ entity.setOwnerEntityId(owner.getEntityId());
+ entity.setDiscRadius(radius);
+ entity.setDiscThickness(thickness);
+ return entity;
+ }
+
+ public EntityAbilityLaser createLaserInternal(World world, Entity owner, double x, double y, double z,
+ float laserWidth) {
+ EntityAbilityLaser entity = new EntityAbilityLaser(world);
+ entity.setPosition(x, y, z);
+ entity.setStartPosition(x, y, z);
+ entity.setOwnerEntityId(owner.getEntityId());
+ entity.setLaserWidth(laserWidth);
+ return entity;
+ }
+
+ public EntityAbilityZone createHazardInternal(World world, Entity owner, double x, double y, double z) {
+ EntityAbilityZone entity = new EntityAbilityZone(world);
+ entity.initAsHazard(owner, x, y, z);
+ return entity;
+ }
+
+ public EntityAbilityZone createTrapInternal(World world, Entity owner, double x, double y, double z) {
+ EntityAbilityZone entity = new EntityAbilityZone(world);
+ entity.initAsTrap(owner, x, y, z);
+ return entity;
+ }
+
+ public EntityEnergySweeper createSweeperInternal(World world, Entity owner, double x, double y, double z) {
+ EntityEnergySweeper entity = new EntityEnergySweeper(world);
+ entity.setPosition(x, y, z);
+ entity.setOwnerEntityId(owner.getEntityId());
+ return entity;
+ }
+
+ public EntityEnergyPanel createPanelInternal(World world, Entity owner, double x, double y, double z) {
+ EntityEnergyPanel entity = new EntityEnergyPanel(world);
+ entity.setPosition(x, y, z);
+ entity.setOwnerEntityId(owner.getEntityId());
+ return entity;
+ }
+
+ public EntityEnergyExplosion createExplosionInternal(World world, Entity owner, double x, double y, double z, float radius) {
+ return new EntityEnergyExplosion(world, owner, x, y, z, radius);
+ }
+
+ // ═══════════════════════════════════════════════════════════════════
+ // IEnergyHandler (Script API methods)
+ // ═══════════════════════════════════════════════════════════════════
+
+ @Override
+ public IEnergyOrb createOrb(IWorld world, IEntity owner, double x, double y, double z, float size) {
+ EntityAbilityOrb entity = createOrbInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, size);
+ return (IEnergyOrb) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergyBeam createBeam(IWorld world, IEntity owner, double x, double y, double z, float beamWidth, float headSize) {
+ EntityAbilityBeam entity = createBeamInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, beamWidth, headSize);
+ return (IEnergyBeam) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergyDisc createDisc(IWorld world, IEntity owner, double x, double y, double z, float radius, float thickness) {
+ EntityAbilityDisc entity = createDiscInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius, thickness);
+ return (IEnergyDisc) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergyLaser createLaser(IWorld world, IEntity owner, double x, double y, double z, float laserWidth) {
+ EntityAbilityLaser entity = createLaserInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, laserWidth);
+ return (IEnergyLaser) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergyZone createHazard(IWorld world, IEntity owner, double x, double y, double z) {
+ EntityAbilityZone entity = createHazardInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
+ return (IEnergyZone) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergyZone createTrap(IWorld world, IEntity owner, double x, double y, double z) {
+ EntityAbilityZone entity = createTrapInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
+ return (IEnergyZone) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergySweeper createSweeper(IWorld world, IEntity owner, double x, double y, double z) {
+ EntityEnergySweeper entity = createSweeperInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
+ return (IEnergySweeper) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergyPanel createPanel(IWorld world, IEntity owner, double x, double y, double z) {
+ EntityEnergyPanel entity = createPanelInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
+ return (IEnergyPanel) NpcAPI.Instance().getIEntity(entity);
+ }
+
+ @Override
+ public IEnergyExplosion createExplosion(IWorld world, IEntity owner, double x, double y, double z, float radius) {
+ EntityEnergyExplosion entity = createExplosionInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius);
+ return new ScriptEnergyExplosion<>(entity);
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/controllers/ProfileController.java b/src/main/java/kamkeel/npcs/controllers/ProfileController.java
index 103da1309..c4be7322e 100644
--- a/src/main/java/kamkeel/npcs/controllers/ProfileController.java
+++ b/src/main/java/kamkeel/npcs/controllers/ProfileController.java
@@ -7,7 +7,9 @@ import kamkeel.npcs.controllers.data.profile.Profile;
import kamkeel.npcs.controllers.data.profile.ProfileInfoEntry;
import kamkeel.npcs.controllers.data.profile.ProfileOperation;
import kamkeel.npcs.controllers.data.profile.Slot;
+import kamkeel.npcs.network.packets.data.ProfileSharedQuestPacket;
import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.CustomNpcs;
@@ -453,6 +455,9 @@ public class ProfileController implements IProfileHandler {
PlayerDataScript handler = ScriptController.Instance.getPlayerScripts(profile.player);
verifySlotQuests(profile.player);
save(profile.player, profile);
+ if (profile.player instanceof EntityPlayerMP) {
+ ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) profile.player);
+ }
IPlayer scriptPlayer = (IPlayer) NpcAPI.Instance().getIEntity(profile.player);
EventHooks.onProfileCreate(handler, scriptPlayer, profile, newSlotId, true);
@@ -523,6 +528,10 @@ public class ProfileController implements IProfileHandler {
// overwrite the destination slot with stale data.
saveSlotData(profile.player, profile, prevSlot);
loadSlotData(profile.player, profile, newSlotId);
+ syncSharedQuestsToPlayer(profile.player);
+ if (profile.player instanceof EntityPlayerMP) {
+ ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) profile.player);
+ }
EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true);
} else {
@@ -832,15 +841,6 @@ public class ProfileController implements IProfileHandler {
else
compound = (NBTTagCompound) compound.copy();
playerData.setNBT(compound);
-
- // Trade data is shared across all profile slots - copy from player's live data
- PlayerData liveData = PlayerData.get(player);
- if (liveData != null) {
- NBTTagCompound tradeCompound = new NBTTagCompound();
- liveData.tradeData.writeToNBT(tradeCompound);
- playerData.tradeData.readFromNBT(tradeCompound);
- }
-
return playerData;
}
@@ -869,6 +869,9 @@ public class ProfileController implements IProfileHandler {
}
}
+ // Update the profile cache
+ profile.sharedQuestTimestamps = universalFinished;
+
// Push the universal shared completion times into every slot.
for (ISlot slot : profile.getSlots().values()) {
IPlayerData data = getSlotPlayerData(player, slot.getId());
@@ -881,22 +884,33 @@ public class ProfileController implements IProfileHandler {
}
}
+ public void syncSharedQuestsToPlayer(EntityPlayer player) {
+ Profile profile = getProfile(player);
+ if (profile == null || profile.sharedQuestTimestamps.isEmpty()) {
+ return;
+ }
+ PlayerQuestData questData = PlayerData.get(player).questData;
+ for (Map.Entry entry : profile.sharedQuestTimestamps.entrySet()) {
+ Long existing = questData.finishedQuests.get(entry.getKey());
+ if (existing == null || entry.getValue() > existing) {
+ questData.finishedQuests.put(entry.getKey(), entry.getValue());
+ }
+ }
+ }
+
public void shareQuestCompletion(EntityPlayer player, int questId, long completeTime) {
Profile profile = getProfile(player);
if (profile == null) {
return;
}
- for (ISlot slot : profile.getSlots().values()) {
- IPlayerData playerData = getSlotPlayerData(player, slot.getId());
- if (playerData != null) {
- PlayerQuestData questData = (PlayerQuestData) playerData.getQuestData();
- Long existing = questData.finishedQuests.get(questId);
- if (existing == null || completeTime > existing) {
- questData.finishedQuests.put(questId, completeTime);
- }
- playerData.save();
- }
+
+ Long existing = profile.sharedQuestTimestamps.get(questId);
+ if (existing == null || completeTime > existing) {
+ profile.sharedQuestTimestamps.put(questId, completeTime);
}
save(player, profile);
+ if (player instanceof EntityPlayerMP) {
+ ProfileSharedQuestPacket.sendToPlayer((EntityPlayerMP) player);
+ }
}
}
diff --git a/src/main/java/kamkeel/npcs/controllers/SyncController.java b/src/main/java/kamkeel/npcs/controllers/SyncController.java
index b6010ad86..56dc377f9 100644
--- a/src/main/java/kamkeel/npcs/controllers/SyncController.java
+++ b/src/main/java/kamkeel/npcs/controllers/SyncController.java
@@ -5,854 +5,339 @@ import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import kamkeel.npcs.addon.DBCAddon;
+import kamkeel.npcs.controllers.sync.SyncHandler;
+import kamkeel.npcs.controllers.sync.SyncRegistry;
+import kamkeel.npcs.controllers.sync.handlers.*;
import kamkeel.npcs.network.LargeAbstractPacket;
import kamkeel.npcs.network.PacketHandler;
import kamkeel.npcs.network.enums.EnumSyncAction;
-import kamkeel.npcs.network.enums.EnumSyncType;
+import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.data.LoginPacket;
-import kamkeel.npcs.network.packets.data.large.SyncEffectPacket;
+import kamkeel.npcs.network.packets.data.ProfileSharedQuestPacket;
import kamkeel.npcs.network.packets.data.large.SyncPacket;
import kamkeel.npcs.network.packets.request.party.PartyInfoPacket;
import kamkeel.npcs.util.ByteBufUtils;
-import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
-import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
+import noppes.npcs.LogWriter;
import noppes.npcs.client.ClientCacheHandler;
-import noppes.npcs.controllers.CustomEffectController;
-import noppes.npcs.controllers.DialogController;
-import noppes.npcs.controllers.FactionController;
-import noppes.npcs.controllers.MagicController;
-import noppes.npcs.controllers.QuestController;
-import noppes.npcs.controllers.RecipeController;
-import noppes.npcs.controllers.data.CustomEffect;
-import noppes.npcs.controllers.data.Dialog;
-import noppes.npcs.controllers.data.DialogCategory;
-import noppes.npcs.controllers.data.EffectKey;
-import noppes.npcs.controllers.data.Faction;
-import noppes.npcs.controllers.data.Magic;
-import noppes.npcs.controllers.data.MagicCycle;
+import noppes.npcs.client.gui.util.IGuiData;
import noppes.npcs.controllers.data.PlayerData;
-import noppes.npcs.controllers.data.PlayerEffect;
-import noppes.npcs.controllers.data.Quest;
-import noppes.npcs.controllers.data.QuestCategory;
-import noppes.npcs.controllers.data.RecipeAnvil;
-import noppes.npcs.controllers.data.RecipeCarpentry;
-import kamkeel.npcs.controllers.data.ability.Ability;
-import kamkeel.npcs.controllers.data.ability.AbilityController;
-import java.io.IOException;
-import java.util.EnumMap;
-import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
+/**
+ * Central sync backend for CNPC+.
+ *
+ * This controller manages two distinct sync lanes:
+ *
+ * - Global cached registry families — registered via {@link SyncRegistry}
+ * with concrete {@link SyncHandler} implementations. These families use
+ * cached serialized payloads, revision-based delta sync on reconnect,
+ * and chunked delivery. All family-specific RELOAD/UPDATE/REMOVE logic
+ * lives in the handler implementations, not here.
+ * - Direct per-player sync helpers — for transient per-player state
+ * like effects, ability hotbars, and cooldowns. These bypass the cached
+ * registry system and are sent as direct packets. Owned by
+ * {@link PlayerEffectSyncHelper} and {@link PlayerAbilitySyncHelper}.
+ *
+ *
+ * This class retains ownership of:
+ *
+ * - Cache entry storage and lazy rebuild ({@link SyncCacheEntry})
+ * - Cached payload byte[] + precomputed chunks ({@link CachedSyncPayload})
+ * - Per-player revision tracking ({@link PlayerSyncState})
+ * - Login handshake and post-login packet sequencing
+ * - Generic sync dispatch helpers (syncAll, syncUpdate, syncRemove)
+ *
+ */
public class SyncController {
- public static boolean DEBUG_SYNC_LOGGING = false;
+ /** Cached serialized reload payloads and revision state for each global sync family. */
+ private static final Map cacheEntries = new LinkedHashMap<>();
- private static final EnumMap cacheEntries = new EnumMap<>(EnumSyncType.class);
+ /** Last known synced revision map for each connected player. */
private static final ConcurrentHashMap playerSyncState = new ConcurrentHashMap<>();
+ /** Stable identity token for the current dedicated-server process, used by the revision handshake. */
+ private static final String SERVER_IDENTITY_KEY = UUID.randomUUID().toString();
- private static void debug(String message, Object... args) {
- if (DEBUG_SYNC_LOGGING) {
- System.out.println("[SyncController] " + String.format(message, args));
- }
+ // ═══════════════════════════════════════════════════════════════════════
+ // Lifecycle — handler registration and cache initialization
+ // ═══════════════════════════════════════════════════════════════════════
+
+ /**
+ * Registers all core CNPC+ sync handlers in deterministic order.
+ * Called on server start. The registration order determines login
+ * sync ordering via {@link SyncRegistry#getLoginTypes()}.
+ *
+ * Handler registration order matches the original hard-coded
+ * LOGIN_SYNC_TYPES array for behavioral parity.
+ */
+ public static void register() {
+ SyncRegistry.register(SyncType.FACTION, new FactionSyncHandler());
+ SyncRegistry.register(SyncType.DIALOG, new DialogSyncHandler());
+ SyncRegistry.register(SyncType.DIALOG_CATEGORY, new DialogCategorySyncHandler());
+ SyncRegistry.register(SyncType.QUEST, new QuestSyncHandler());
+ SyncRegistry.register(SyncType.QUEST_CATEGORY, new QuestCategorySyncHandler());
+ SyncRegistry.register(SyncType.PLAYERDATA, new PlayerDataSyncHandler());
+ SyncRegistry.register(SyncType.WORKBENCH_RECIPES, new WorkbenchRecipeSyncHandler());
+ SyncRegistry.register(SyncType.CARPENTRY_RECIPES, new CarpentryRecipeSyncHandler());
+ SyncRegistry.register(SyncType.ANVIL_RECIPES, new AnvilRecipeSyncHandler());
+ SyncRegistry.register(SyncType.CUSTOM_EFFECTS, new CustomEffectSyncHandler());
+ SyncRegistry.register(SyncType.MAGIC, new MagicSyncHandler());
+ SyncRegistry.register(SyncType.MAGIC_CYCLE, new MagicCycleSyncHandler());
+ SyncRegistry.register(SyncType.CUSTOM_ABILITY, new CustomAbilitySyncHandler());
+ SyncRegistry.register(SyncType.CHAINED_ABILITY, new ChainedAbilitySyncHandler());
}
-
- private static final EnumSyncType[] LOGIN_SYNC_TYPES = new EnumSyncType[]{
- EnumSyncType.FACTION,
- EnumSyncType.DIALOG_CATEGORY,
- EnumSyncType.QUEST_CATEGORY,
- EnumSyncType.WORKBENCH_RECIPES,
- EnumSyncType.CARPENTRY_RECIPES,
- EnumSyncType.ANVIL_RECIPES,
- EnumSyncType.CUSTOM_EFFECTS,
- EnumSyncType.MAGIC,
- EnumSyncType.MAGIC_CYCLE,
- EnumSyncType.CUSTOM_ABILITY
- };
-
+
public static void load() {
cacheEntries.clear();
playerSyncState.clear();
- registerCache(EnumSyncType.FACTION, SyncController::factionsNBT);
- registerCache(EnumSyncType.DIALOG_CATEGORY, SyncController::dialogCategoriesNBT);
- registerCache(EnumSyncType.QUEST_CATEGORY, SyncController::questCategoriesNBT);
- registerCache(EnumSyncType.WORKBENCH_RECIPES, SyncController::workbenchNBT);
- registerCache(EnumSyncType.CARPENTRY_RECIPES, SyncController::carpentryNBT);
- registerCache(EnumSyncType.ANVIL_RECIPES, SyncController::anvilNBT);
- registerCache(EnumSyncType.CUSTOM_EFFECTS, SyncController::customEffectsNBT);
- registerCache(EnumSyncType.MAGIC, SyncController::magicsNBT);
- registerCache(EnumSyncType.MAGIC_CYCLE, SyncController::magicCyclesNBT);
- registerCache(EnumSyncType.CUSTOM_ABILITY, SyncController::customAbilitiesNBT);
+ // Register caches for all cached (login-sync) types
+ // The cache supplier delegates to the handler's serializeAll()
+ for (SyncType type : SyncRegistry.getLoginTypes()) {
+ SyncHandler handler = SyncRegistry.getHandler(type);
+ if (handler != null)
+ registerCache(type, handler::serializeAll);
+ }
}
- public static void syncPlayer(EntityPlayerMP player) {
- SyncController.syncPlayerInternal(player, true);
+
+ // ═══════════════════════════════════════════════════════════════════════
+ // Other Login syncers
+ // ═══════════════════════════════════════════════════════════════════════
+
+ public static void beginLogin(EntityPlayerMP player) {
+ playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
+ PacketHandler.Instance.sendToPlayer(new LoginPacket(getServerCacheKey(), getServerRevisionSnapshot()), player);
}
- private static void syncPlayerInternal(EntityPlayerMP player, boolean includePostPackets) {
+ private static void sendPostLoginPackets(EntityPlayerMP player) {
+ DBCAddon.instance.syncPlayer(player);
+ PlayerDataSyncHandler.syncPlayerData(player, false);
+ PartyInfoPacket.sendPartyData(player);
+ ProfileSharedQuestPacket.sendToPlayer(player);
+
+ // Sync skin overlays after full handshake to ensure the client is ready.
+ // Overlays are not part of getSyncNBTFull(), and packets sent during
+ // PlayerLoggedInEvent can arrive before the client entity exists.
+ PlayerData data = PlayerData.get(player);
+ if (data != null) data.skinOverlays.updateClient();
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════
+ // MAIN PIPELINE — completion of login handshake and full catalog sync
+ // ═══════════════════════════════════════════════════════════════════════
+
+ /**
+ * Runs the cached-family sync pass for one player using the currently tracked
+ * revision state. Used after the login handshake and by server-side callers
+ * that need to refresh a player's global cached sync families.
+ */
+ public static void dispatchSyncForAllTypes(EntityPlayerMP player) {
PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
- for (EnumSyncType type : LOGIN_SYNC_TYPES) {
+ // Registry-driven login iteration: iterate only cached types
+ for (SyncType type : SyncRegistry.getLoginTypes()) {
SyncCacheEntry entry = cacheEntries.get(type);
- if (entry == null) {
- continue;
- }
+ if (entry == null) continue;
int currentRevision = entry.getRevisionValue();
int lastRevision = state.getRevision(type);
- if (lastRevision == currentRevision) {
- continue;
- }
-
+ if (lastRevision == currentRevision) continue;
+
CachedSyncPayload payload = entry.getPayload(type);
- if (payload == null) {
- continue;
- }
+ if (payload == null) continue;
if (lastRevision != payload.getRevision()) {
- debug("Sending %s data to %s", type, player.getCommandSenderName());
PacketHandler.Instance.sendToPlayer(new SyncPacket(type, payload), player);
state.updateRevision(type, payload.getRevision());
}
}
- if (includePostPackets) {
- sendPostLoginPackets(player);
- }
- }
-
- public static void beginLogin(EntityPlayerMP player) {
- playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
- PacketHandler.Instance.sendToPlayer(
- new LoginPacket(getServerCacheKey(), getServerRevisionSnapshot()),
- player
- );
- }
-
- public static void handleClientRevisionReport(
- EntityPlayerMP player,
- String serverKey,
- String previousServerKey,
- Map clientRevisions
- ) {
- String currentServerKey = getServerCacheKey();
- PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
-
- if (!currentServerKey.equals(serverKey)) {
- state.reset();
- syncPlayer(player);
- return;
- }
-
- if (!currentServerKey.isEmpty()) {
- if (previousServerKey == null || !currentServerKey.equals(previousServerKey)) {
- state.reset();
- syncPlayer(player);
- return;
- }
- }
-
- if (clientRevisions == null || clientRevisions.isEmpty()) {
- debug(
- "Client %s reported no cached revisions; forcing full sync",
- player.getCommandSenderName()
- );
- state.reset();
- } else {
- state.applyHandshake(clientRevisions);
- }
-
- syncPlayer(player);
- }
-
- private static void sendPostLoginPackets(EntityPlayerMP player) {
- DBCAddon.instance.syncPlayer(player);
- syncPlayerData(player, false);
- PartyInfoPacket.sendPartyData(player);
- }
-
- private static EnumMap getServerRevisionSnapshot() {
- EnumMap snapshot = new EnumMap<>(EnumSyncType.class);
- for (EnumSyncType type : LOGIN_SYNC_TYPES) {
- SyncCacheEntry entry = cacheEntries.get(type);
- if (entry != null) {
- snapshot.put(type, entry.getRevisionValue());
- }
- }
- return snapshot;
- }
-
- private static final String SERVER_IDENTITY_KEY = UUID.randomUUID().toString();
-
- private static String getServerCacheKey() {
- MinecraftServer server = MinecraftServer.getServer();
- if (server == null) {
- return "";
- }
-
- if (!server.isDedicatedServer()) {
- return "";
- }
-
- return SERVER_IDENTITY_KEY;
- }
-
- public static int getCurrentRevision(EnumSyncType type) {
- SyncCacheEntry entry = cacheEntries.get(type);
- return entry == null ? -1 : entry.getRevisionValue();
- }
-
- public static NBTTagCompound workbenchNBT() {
- 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;
- }
-
- public static NBTTagCompound carpentryNBT() {
- 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;
- }
-
- public static NBTTagCompound anvilNBT() {
- 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;
- }
-
- public static NBTTagCompound factionsNBT() {
- NBTTagList list = new NBTTagList();
- NBTTagCompound compound = new NBTTagCompound();
- for (Faction faction : FactionController.getInstance().factions.values()) {
- NBTTagCompound factioNBT = new NBTTagCompound();
- faction.writeNBT(factioNBT);
- list.appendTag(factioNBT);
- }
- compound.setTag("Factions", list);
- return compound;
- }
-
- public static NBTTagCompound dialogCategoriesNBT() {
- 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;
- }
-
- public static NBTTagCompound questCategoriesNBT() {
- 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;
- }
-
- public static NBTTagCompound customEffectsNBT() {
- 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;
- }
-
- public static NBTTagCompound magicsNBT() {
- 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;
- }
-
- public static NBTTagCompound magicCyclesNBT() {
- 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;
- }
-
- public static NBTTagCompound customAbilitiesNBT() {
- NBTTagList list = new NBTTagList();
- NBTTagCompound compound = new NBTTagCompound();
- for (Map.Entry entry : AbilityController.Instance.getCustomAbilities().entrySet()) {
- NBTTagCompound abilityNBT = entry.getValue().writeNBT();
- abilityNBT.setString("CustomAbilityId", entry.getKey());
- list.appendTag(abilityNBT);
- }
- compound.setTag("Data", list);
- return compound;
- }
-
- public static void syncAllCustomAbilities() {
- CachedSyncPayload payload = rebuildNow(EnumSyncType.CUSTOM_ABILITY);
- if (payload == null) {
- return;
- }
- PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CUSTOM_ABILITY, payload));
- updateAllPlayerRevisions(EnumSyncType.CUSTOM_ABILITY, payload.getRevision());
- }
-
- public static void syncPlayerData(EntityPlayerMP player, boolean update) {
- PlayerData data = PlayerData.get(player);
- if (data != null) {
- if (update) {
- PacketHandler.Instance.sendToPlayer(new SyncPacket(
- EnumSyncType.PLAYERDATA,
- EnumSyncAction.UPDATE,
- -1,
- data.getSyncNBT())
- , player);
- } else {
- PacketHandler.Instance.sendToPlayer(new SyncPacket(
- EnumSyncType.PLAYERDATA,
- EnumSyncAction.RELOAD,
- -1,
- data.getSyncNBTFull()), player);
- }
- }
- }
-
- public static void syncRemove(EnumSyncType enumSyncType, int id) {
- Map revisions = invalidateCaches(enumSyncType);
- int revision = revisions.getOrDefault(enumSyncType, getCurrentRevision(enumSyncType));
- PacketHandler.Instance.sendToAll(new SyncPacket(
- enumSyncType,
- EnumSyncAction.REMOVE,
- id,
- revision,
- new NBTTagCompound()
- ));
- updateAllPlayerRevisions(revisions);
- }
-
- public static void syncAllDialogs() {
- CachedSyncPayload payload = rebuildNow(EnumSyncType.DIALOG_CATEGORY);
- if (payload == null) {
- return;
- }
- PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.DIALOG_CATEGORY, payload));
- updateAllPlayerRevisions(EnumSyncType.DIALOG_CATEGORY, payload.getRevision());
- }
-
- public static void syncAllQuests() {
- CachedSyncPayload payload = rebuildNow(EnumSyncType.QUEST_CATEGORY);
- if (payload == null) {
- return;
- }
- PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.QUEST_CATEGORY, payload));
- updateAllPlayerRevisions(EnumSyncType.QUEST_CATEGORY, payload.getRevision());
- }
-
- public static void syncAllWorkbenchRecipes() {
- CachedSyncPayload payload = rebuildNow(EnumSyncType.WORKBENCH_RECIPES);
- if (payload == null) {
- return;
- }
- PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.WORKBENCH_RECIPES, payload));
- updateAllPlayerRevisions(EnumSyncType.WORKBENCH_RECIPES, payload.getRevision());
- }
-
- public static void syncAllCarpentryRecipes() {
- CachedSyncPayload payload = rebuildNow(EnumSyncType.CARPENTRY_RECIPES);
- if (payload == null) {
- return;
- }
- PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CARPENTRY_RECIPES, payload));
- updateAllPlayerRevisions(EnumSyncType.CARPENTRY_RECIPES, payload.getRevision());
- }
-
- public static void syncAllAnvilRecipes() {
- CachedSyncPayload payload = rebuildNow(EnumSyncType.ANVIL_RECIPES);
- if (payload == null) {
- return;
- }
- PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.ANVIL_RECIPES, payload));
- updateAllPlayerRevisions(EnumSyncType.ANVIL_RECIPES, payload.getRevision());
- }
-
- public static void syncAllCustomEffects() {
- CachedSyncPayload payload = rebuildNow(EnumSyncType.CUSTOM_EFFECTS);
- if (payload == null) {
- return;
- }
- PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CUSTOM_EFFECTS, payload));
- updateAllPlayerRevisions(EnumSyncType.CUSTOM_EFFECTS, payload.getRevision());
- }
-
- @SideOnly(Side.CLIENT)
- public static void clientSync(EnumSyncType enumSyncType, int revision, NBTTagCompound fullCompound) {
- switch (enumSyncType) {
- case FACTION: {
- 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();
- break;
- }
- case DIALOG_CATEGORY: {
- 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 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();
- break;
- }
- case QUEST_CATEGORY: {
- 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 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();
- break;
- }
- case PLAYERDATA: {
- ClientCacheHandler.playerData.setSyncNBTFull(fullCompound);
- break;
- }
- case MAGIC: {
- 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();
- break;
- }
- case MAGIC_CYCLE: {
- 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();
- break;
- }
- case WORKBENCH_RECIPES: {
- 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();
- break;
- }
- case CARPENTRY_RECIPES: {
- 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();
- break;
- }
- case ANVIL_RECIPES: {
- 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();
- break;
- }
- case CUSTOM_EFFECTS: {
- 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();
- break;
- }
- case CUSTOM_ABILITY: {
- NBTTagList list = fullCompound.getTagList("Data", 10);
- LinkedHashMap sync = new LinkedHashMap<>();
- for (int i = 0; i < list.tagCount(); i++) {
- NBTTagCompound nbt = list.getCompoundTagAt(i);
- String uuid = nbt.getString("CustomAbilityId");
- Ability ability = AbilityController.Instance.fromNBT(nbt);
- if (ability != null) {
- ability.setId(uuid);
- sync.put(uuid, ability);
- }
- }
- AbilityController.Instance.setCustomAbilities(sync);
- break;
- }
- }
-
- ClientCacheHandler.updateClientRevision(enumSyncType, revision);
+ sendPostLoginPackets(player);
}
/**
- * Update Related Tasks
+ * Completes the server-side revision handshake that follows {@link LoginPacket}.
+ *
+ * The client reports which cached revisions it believes are still valid for the
+ * current server identity. If the reported server identity is stale or missing,
+ * we reset the stored state and force a full cached resync. Otherwise we seed the
+ * player's tracked revisions from the client report and only send outdated families.
*/
- @SideOnly(Side.CLIENT)
- public static void clientUpdate(EnumSyncType enumSyncType, int category_id, int revision, NBTTagCompound compound) {
- switch (enumSyncType) {
- case FACTION: {
- Faction faction = new Faction();
- faction.readNBT(compound);
- FactionController.getInstance().factions.put(faction.id, faction);
- break;
- }
- case DIALOG: {
- DialogCategory category = DialogController.Instance.categories.get(category_id);
- Dialog dialog = new Dialog();
- dialog.category = category;
- dialog.readNBT(compound);
- DialogController.Instance.dialogs.put(dialog.id, dialog);
- category.dialogs.put(dialog.id, dialog);
- break;
- }
- case QUEST: {
- QuestCategory category = QuestController.Instance.categories.get(category_id);
- Quest quest = new Quest();
- quest.category = category;
- quest.readNBT(compound);
- QuestController.Instance.quests.put(quest.id, quest);
- category.quests.put(quest.id, quest);
- break;
- }
- case QUEST_CATEGORY: {
- 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);
- break;
- }
- case DIALOG_CATEGORY: {
- 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);
- break;
- }
- case MAGIC_CYCLE: {
- MagicCycle cycle = new MagicCycle();
- cycle.readNBT(compound);
- MagicController.getInstance().cycles.put(cycle.id, cycle);
- break;
- }
- case MAGIC: {
- Magic magic = new Magic();
- magic.readNBT(compound);
- MagicController.getInstance().magics.put(magic.id, magic);
- break;
- }
- case PLAYERDATA: {
- ClientCacheHandler.playerData.setSyncNBT(compound);
- break;
- }
- case CUSTOM_EFFECTS: {
- CustomEffect effect = new CustomEffect();
- effect.readFromNBT(compound);
- ClientCacheHandler.getImageData(effect.icon);
+ public static void completeLoginRevisionHandshake(EntityPlayerMP player, String serverKey, String previousServerKey,
+ Map clientRevisions) {
+ String currentServerKey = getServerCacheKey();
+ PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
- CustomEffectController.Instance.getCustomEffects().put(effect.id, effect);
- break;
- }
- }
+ boolean serverIdentityMismatch = !currentServerKey.equals(serverKey);
+ boolean previousServerMismatch = !currentServerKey.isEmpty() && (previousServerKey == null || !currentServerKey.equals(
+ previousServerKey));
+ boolean canReuseClientRevisions = clientRevisions != null && !clientRevisions.isEmpty();
- ClientCacheHandler.updateClientRevision(enumSyncType, revision);
+ // Any server identity mismatch means the client's cached revision map is unsafe to reuse.
+ if (serverIdentityMismatch || previousServerMismatch || !canReuseClientRevisions)
+ state.reset();
+ else // The client and server agree on identity, so seed the stored state from the report.
+ state.applyHandshake(clientRevisions);
+
+ dispatchSyncForAllTypes(player);
}
- public static void syncUpdate(EnumSyncType type, int cat, NBTTagCompound compound) {
- Map revisions = invalidateCaches(type);
- int revision = revisions.getOrDefault(type, getCurrentRevision(type));
- PacketHandler.Instance.sendToAll(new SyncPacket(
- type,
- EnumSyncAction.UPDATE,
- cat,
- revision,
- compound
- ));
+
+ // ═══════════════════════════════════════════════════════════════════════
+ // Generic dispatcher — called from outside SyncController
+ // ═══════════════════════════════════════════════════════════════════════
+
+ /**
+ * Generic full-broadcast helper. Rebuilds the cache for the given type
+ * and sends to all connected players.
+ */
+ public static void syncAll(SyncType type) {
+ CachedSyncPayload payload = rebuildCache(type);
+ if (payload == null) return;
+
+ PacketHandler.Instance.sendToAll(new SyncPacket(type, payload));
+ updateAllPlayerRevisions(type, payload.getRevision());
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════
+ // Player data sync
+ // ═══════════════════════════════════════════════════════════════════════
+
+ public static void syncPlayerData(SyncType type, NBTTagCompound compound, boolean fullData, EntityPlayerMP player) {
+ Map revisions = invalidateCaches(type);
+ int revision = getRequestedInvalidationRevision(type, revisions);
+ PacketHandler.Instance.sendToPlayer(
+ new SyncPacket(type, EnumSyncAction.UPDATE, fullData ? 1 : 0, null, revision, compound), player);
+ updateAllPlayerRevisions(revisions);
+ }
+
+ // ═══════════════════════════════════════════════════════════════════════
+ // Server-side dispatchers — registry-driven
+ // ═══════════════════════════════════════════════════════════════════════
+ public static void syncUpdate(SyncType type, NBTTagCompound compound) {
+ Map revisions = invalidateCaches(type);
+ int revision = getRequestedInvalidationRevision(type, revisions);
+ PacketHandler.Instance.sendToAll(new SyncPacket(type, EnumSyncAction.UPDATE, -1, null, revision, compound));
+ updateAllPlayerRevisions(revisions);
+ }
+
+ public static void syncUpdate(SyncType type, String key, NBTTagCompound compound) {
+ Map revisions = invalidateCaches(type);
+ int revision = getRequestedInvalidationRevision(type, revisions);
+ PacketHandler.Instance.sendToAll(new SyncPacket(type, EnumSyncAction.UPDATE, -1, key, revision, compound));
+ updateAllPlayerRevisions(revisions);
+ }
+
+ public static void syncUpdate(SyncType type, int cat, NBTTagCompound compound) {
+ Map revisions = invalidateCaches(type);
+ int revision = getRequestedInvalidationRevision(type, revisions);
+ PacketHandler.Instance.sendToAll(new SyncPacket(type, EnumSyncAction.UPDATE, cat, null, revision, compound));
+ updateAllPlayerRevisions(revisions);
+ }
+
+ public static void syncRemove(SyncType syncType, String key) {
+ Map revisions = invalidateCaches(syncType);
+ int revision = getRequestedInvalidationRevision(syncType, revisions);
+ PacketHandler.Instance.sendToAll(new SyncPacket(syncType, EnumSyncAction.REMOVE, -1, key, revision, null));
+ updateAllPlayerRevisions(revisions);
+ }
+
+ public static void syncRemove(SyncType syncType, int id) {
+ Map revisions = invalidateCaches(syncType);
+ int revision = getRequestedInvalidationRevision(syncType, revisions);
+ PacketHandler.Instance.sendToAll(new SyncPacket(syncType, EnumSyncAction.REMOVE, id, null, revision, null));
updateAllPlayerRevisions(revisions);
}
- public static NBTTagCompound updateQuestCat(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 handlers — registry-driven handler delegation
+ // ═══════════════════════════════════════════════════════════════════════
- public static NBTTagCompound updateDialogCat(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()));
+ @SideOnly(Side.CLIENT)
+ public static void clientHandleAll(SyncType syncType, int revision, NBTTagCompound fullCompound) {
+ SyncHandler handler = SyncRegistry.getHandler(syncType);
+ if (handler == null) return;
+ try {
+ handler.clientHandleReload(fullCompound);
+ } catch (Exception e) {
+ LogWriter.error("[SyncController] Failed to handle RELOAD for sync type " + syncType, e);
}
- dialogCompound.setTag("Data", dialogList);
- dialogCompound.setTag("CatNBT", dialogCategory.writeSmallNBT(new NBTTagCompound()));
- return dialogCompound;
+ ClientCacheHandler.updateClientRevision(syncType, revision);
+
}
@SideOnly(Side.CLIENT)
- public static void clientSyncRemove(EnumSyncType enumSyncType, int id, int revision) {
- switch (enumSyncType) {
- case FACTION:
- FactionController.getInstance().factions.remove(id);
- break;
- case DIALOG:
- Dialog dialog = DialogController.Instance.dialogs.remove(id);
- if (dialog != null) {
- dialog.category.dialogs.remove(id);
- }
- break;
- case DIALOG_CATEGORY:
- DialogCategory dialogCategory = DialogController.Instance.categories.remove(id);
- if (dialogCategory != null) {
- DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet());
- }
- break;
- case QUEST:
- Quest quest = QuestController.Instance.quests.remove(id);
- if (quest != null) {
- quest.category.quests.remove(id);
- }
- break;
- case QUEST_CATEGORY:
- QuestCategory questCategory = QuestController.Instance.categories.remove(id);
- if (questCategory != null) {
- QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet());
- }
- break;
- case MAGIC:
- for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
- cycle.associations.remove(id);
- }
- MagicController.getInstance().cycles.remove(id);
- break;
- case MAGIC_CYCLE:
- MagicController.getInstance().cycles.remove(id);
- break;
- case CUSTOM_EFFECTS:
- CustomEffectController.Instance.getCustomEffects().remove(id);
- break;
+ public static void clientHandleUpdate(SyncType syncType, int id, String key, int revision, NBTTagCompound compound) {
+ SyncHandler handler = SyncRegistry.getHandler(syncType);
+ if (handler == null) return;
+ try {
+ handler.clientHandleUpdate(compound);
+ handler.clientHandleUpdate(compound, id);
+ handler.clientHandleUpdate(compound, key);
+ } catch (Exception e) {
+ LogWriter.error("[SyncController] Failed to handle UPDATE for sync type " + syncType, e);
}
-
- ClientCacheHandler.updateClientRevision(enumSyncType, revision);
- }
-
- public static void syncEffects(EntityPlayerMP playerMP) {
- ConcurrentHashMap 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);
+
+ ClientCacheHandler.updateClientRevision(syncType, revision);
+
+ // New GUI data handling approach
+ IGuiData.notifyUpdate(compound, key, id);
}
@SideOnly(Side.CLIENT)
- public static void clientSyncEffects(NBTTagCompound compound) {
- PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer);
- if (playerData != null) {
- playerData.setPlayerEffects(compound);
+ public static void clientHandleRemove(SyncType syncType, int id, String key, int revision) {
+ SyncHandler handler = SyncRegistry.getHandler(syncType);
+ if (handler == null) return;
+ try {
+ handler.clientHandleRemove(id);
+ handler.clientHandleRemove(key);
+ } catch (Exception e) {
+ LogWriter.error("[SyncController] Failed to handle REMOVE for sync type " + syncType, e);
}
+
+ ClientCacheHandler.updateClientRevision(syncType, revision);
+
+ // New GUI data handling approach
+ IGuiData.notifyRemove(key, id);
}
- private static void registerCache(EnumSyncType type, Supplier supplier) {
- cacheEntries.put(type, new SyncCacheEntry(type, supplier));
+ // ═══════════════════════════════════════════════════════════════════════
+ // Cache and revision internals
+ // ═══════════════════════════════════════════════════════════════════════
+
+ private static void registerCache(SyncType type, Supplier supplier) {
+ cacheEntries.put(type, new SyncCacheEntry(supplier));
}
- private static CachedSyncPayload rebuildNow(EnumSyncType type) {
+ private static CachedSyncPayload rebuildCache(SyncType type) {
SyncCacheEntry entry = cacheEntries.get(type);
- if (entry == null) {
- return null;
- }
+ if (entry == null) return null;
+
entry.invalidate();
return entry.getPayload(type);
}
- public static Map invalidateCaches(EnumSyncType type) {
- EnumSet targets = getInvalidationTargets(type);
- EnumMap revisions = new EnumMap<>(EnumSyncType.class);
- for (EnumSyncType target : targets) {
+ /**
+ * Registry-driven invalidation: delegates to handler-owned
+ * invalidation targets via {@link SyncRegistry#getInvalidationTargets}.
+ */
+ private static Map invalidateCaches(SyncType type) {
+ Set targets = SyncRegistry.getInvalidationTargets(type);
+ Map revisions = new LinkedHashMap<>();
+ for (SyncType target : targets) {
SyncCacheEntry entry = cacheEntries.get(target);
if (entry != null) {
int newRevision = entry.invalidate();
@@ -862,55 +347,55 @@ public class SyncController {
return revisions;
}
- private static EnumSet getInvalidationTargets(EnumSyncType type) {
- switch (type) {
- case DIALOG:
- case DIALOG_CATEGORY:
- return EnumSet.of(EnumSyncType.DIALOG_CATEGORY);
- case QUEST:
- case QUEST_CATEGORY:
- return EnumSet.of(EnumSyncType.QUEST_CATEGORY);
- case FACTION:
- return EnumSet.of(EnumSyncType.FACTION);
- case MAGIC:
- return EnumSet.of(EnumSyncType.MAGIC);
- case MAGIC_CYCLE:
- return EnumSet.of(EnumSyncType.MAGIC_CYCLE);
- case WORKBENCH_RECIPES:
- return EnumSet.of(EnumSyncType.WORKBENCH_RECIPES);
- case CARPENTRY_RECIPES:
- return EnumSet.of(EnumSyncType.CARPENTRY_RECIPES);
- case ANVIL_RECIPES:
- return EnumSet.of(EnumSyncType.ANVIL_RECIPES);
- case CUSTOM_EFFECTS:
- return EnumSet.of(EnumSyncType.CUSTOM_EFFECTS);
- case CUSTOM_ABILITY:
- return EnumSet.of(EnumSyncType.CUSTOM_ABILITY);
- default:
- return EnumSet.noneOf(EnumSyncType.class);
- }
+ private static int getRequestedInvalidationRevision(SyncType type, Map revisions) {
+ Integer revision = revisions.get(type);
+ return revision != null ? revision : getCurrentServerRevision(type);
}
- private static void updateAllPlayerRevisions(EnumSyncType type, int revision) {
- if (revision < 0) {
- return;
+ public static int getCurrentServerRevision(SyncType type) {
+ SyncCacheEntry entry = cacheEntries.get(type);
+ return entry == null ? -1 : entry.getRevisionValue();
+ }
+
+ private static Map getServerRevisionSnapshot() {
+ // Registry-driven: iterate login types from registry
+ Map snapshot = new LinkedHashMap<>();
+ for (SyncType type : SyncRegistry.getLoginTypes()) {
+ SyncCacheEntry entry = cacheEntries.get(type);
+ if (entry != null)
+ snapshot.put(type, entry.getRevisionValue());
}
- for (PlayerSyncState state : playerSyncState.values()) {
+ return snapshot;
+ }
+
+ private static void updateAllPlayerRevisions(SyncType type, int revision) {
+ if (revision < 0) return;
+
+ for (PlayerSyncState state : playerSyncState.values())
state.updateRevision(type, revision);
+ }
+
+ private static void updateAllPlayerRevisions(Map revisions) {
+ if (revisions.isEmpty()) return;
+
+ for (PlayerSyncState state : playerSyncState.values()) {
+ for (Map.Entry entry : revisions.entrySet())
+ state.updateRevision(entry.getKey(), entry.getValue());
}
}
- private static void updateAllPlayerRevisions(Map revisions) {
- if (revisions.isEmpty()) {
- return;
- }
- for (PlayerSyncState state : playerSyncState.values()) {
- for (Map.Entry entry : revisions.entrySet()) {
- state.updateRevision(entry.getKey(), entry.getValue());
- }
- }
+ private static String getServerCacheKey() {
+ MinecraftServer server = MinecraftServer.getServer();
+ if (server == null || !server.isDedicatedServer()) return "";
+
+ return SERVER_IDENTITY_KEY;
}
+
+ // ═══════════════════════════════════════════════════════════════════════
+ // Inner classes — cache payload and player revision state
+ // ═══════════════════════════════════════════════════════════════════════
+
public static final class CachedSyncPayload {
private final int revision;
private final byte[] payload;
@@ -941,20 +426,19 @@ public class SyncController {
private int revision = 0;
private boolean dirty = true;
- private SyncCacheEntry(EnumSyncType type, Supplier supplier) {
+ private SyncCacheEntry(Supplier supplier) {
this.supplier = supplier;
}
- private synchronized CachedSyncPayload getPayload(EnumSyncType requestedType) {
- if (!dirty && payload != null) {
- return payload;
- }
+ private synchronized CachedSyncPayload getPayload(SyncType requestedType) {
+ if (!dirty && payload != null) return payload;
int payloadRevision = revision;
- NBTTagCompound data = supplier.get();
ByteBuf buffer = Unpooled.buffer();
byte[] bytes;
try {
+ NBTTagCompound data = supplier.get();
+
buffer.writeInt(requestedType.ordinal());
buffer.writeInt(EnumSyncAction.RELOAD.ordinal());
buffer.writeInt(-1);
@@ -963,8 +447,9 @@ public class SyncController {
bytes = new byte[buffer.readableBytes()];
buffer.readBytes(bytes);
- } catch (IOException e) {
- throw new RuntimeException("Failed to serialize sync payload for " + requestedType, e);
+ } catch (Exception e) {
+ LogWriter.error("Failed to serialize sync payload for " + requestedType, e);
+ return null;
} finally {
buffer.release();
}
@@ -975,6 +460,23 @@ public class SyncController {
return payload;
}
+ private static byte[][] splitIntoChunks(byte[] payload) {
+ int totalSize = payload.length;
+ int chunkCount = (totalSize + LargeAbstractPacket.CHUNK_SIZE - 1) / LargeAbstractPacket.CHUNK_SIZE;
+ if (chunkCount <= 0)
+ chunkCount = 1;
+
+ byte[][] chunks = new byte[chunkCount][];
+ for (int i = 0; i < chunkCount; i++) {
+ int offset = i * LargeAbstractPacket.CHUNK_SIZE;
+ int length = Math.min(LargeAbstractPacket.CHUNK_SIZE, totalSize - offset);
+ byte[] chunk = new byte[length];
+ System.arraycopy(payload, offset, chunk, 0, length);
+ chunks[i] = chunk;
+ }
+ return chunks;
+ }
+
private synchronized int invalidate() {
dirty = true;
payload = null;
@@ -991,50 +493,30 @@ public class SyncController {
payload = null;
revision = 0;
}
-
- private static byte[][] splitIntoChunks(byte[] payload) {
- int totalSize = payload.length;
- int chunkCount = (totalSize + LargeAbstractPacket.CHUNK_SIZE - 1) / LargeAbstractPacket.CHUNK_SIZE;
- if (chunkCount <= 0) {
- chunkCount = 1;
- }
- byte[][] chunks = new byte[chunkCount][];
- for (int i = 0; i < chunkCount; i++) {
- int offset = i * LargeAbstractPacket.CHUNK_SIZE;
- int length = Math.min(LargeAbstractPacket.CHUNK_SIZE, totalSize - offset);
- byte[] chunk = new byte[length];
- System.arraycopy(payload, offset, chunk, 0, length);
- chunks[i] = chunk;
- }
- return chunks;
- }
}
private static final class PlayerSyncState {
- private final EnumMap revisions = new EnumMap<>(EnumSyncType.class);
+ private final Map revisions = new HashMap<>();
private PlayerSyncState(UUID ignored) {
}
- private synchronized int getRevision(EnumSyncType type) {
+ private synchronized int getRevision(SyncType type) {
Integer value = revisions.get(type);
return value == null ? -1 : value;
}
- private synchronized void updateRevision(EnumSyncType type, int revision) {
+ private synchronized void updateRevision(SyncType type, int revision) {
revisions.put(type, revision);
}
- private synchronized void applyHandshake(Map incoming) {
- if (incoming == null || incoming.isEmpty()) {
- return;
- }
+ private synchronized void applyHandshake(Map incoming) {
+ if (incoming == null || incoming.isEmpty()) return;
revisions.putAll(incoming);
}
private synchronized void reset() {
revisions.clear();
}
-
}
}
diff --git a/src/main/java/kamkeel/npcs/controllers/SyncControllerOld.java b/src/main/java/kamkeel/npcs/controllers/SyncControllerOld.java
new file mode 100644
index 000000000..05f37e8e9
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/controllers/SyncControllerOld.java
@@ -0,0 +1,1058 @@
+//package kamkeel.npcs.controllers;
+//
+//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.addon.DBCAddon;
+//import kamkeel.npcs.controllers.data.ability.Ability;
+//import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
+//import kamkeel.npcs.network.LargeAbstractPacket;
+//import kamkeel.npcs.network.PacketHandler;
+//import kamkeel.npcs.network.enums.EnumSyncAction;
+//import kamkeel.npcs.network.enums.SyncType;
+//import kamkeel.npcs.network.packets.data.LoginPacket;
+//import kamkeel.npcs.network.packets.data.ProfileSharedQuestPacket;
+//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 kamkeel.npcs.network.packets.data.large.SyncEffectPacket;
+//import kamkeel.npcs.network.packets.data.large.SyncPacket;
+//import kamkeel.npcs.network.packets.request.party.PartyInfoPacket;
+//import kamkeel.npcs.util.ByteBufUtils;
+//import net.minecraft.client.Minecraft;
+//import net.minecraft.entity.player.EntityPlayerMP;
+//import net.minecraft.nbt.NBTTagCompound;
+//import net.minecraft.nbt.NBTTagList;
+//import net.minecraft.server.MinecraftServer;
+//import noppes.npcs.client.ClientCacheHandler;
+//import noppes.npcs.controllers.*;
+//import noppes.npcs.controllers.data.*;
+//
+//import java.io.IOException;
+//import java.util.*;
+//import java.util.concurrent.ConcurrentHashMap;
+//import java.util.function.Supplier;
+//
+//public class SyncControllerOld {
+//
+// public static boolean DEBUG_SYNC_LOGGING = false;
+//
+// private static final Map cacheEntries = new LinkedHashMap<>();
+// private static final ConcurrentHashMap playerSyncState = new ConcurrentHashMap<>();
+//
+//
+// private static void debug(String message, Object... args) {
+// if (DEBUG_SYNC_LOGGING) {
+// System.out.println("[SyncController] " + String.format(message, args));
+// }
+// }
+//
+// private static final SyncType[] LOGIN_SYNC_TYPES = new SyncType[]{
+// SyncType.FACTION,
+// SyncType.DIALOG_CATEGORY,
+// SyncType.QUEST_CATEGORY,
+// SyncType.WORKBENCH_RECIPES,
+// SyncType.CARPENTRY_RECIPES,
+// SyncType.ANVIL_RECIPES,
+// SyncType.CUSTOM_EFFECTS,
+// SyncType.MAGIC,
+// SyncType.MAGIC_CYCLE,
+// SyncType.CUSTOM_ABILITY,
+// SyncType.CHAINED_ABILITY
+// };
+//
+// public static void load() {
+// cacheEntries.clear();
+// playerSyncState.clear();
+//
+// registerCache(SyncType.FACTION, SyncControllerOld::factionsNBT);
+// registerCache(SyncType.DIALOG_CATEGORY, SyncControllerOld::dialogCategoriesNBT);
+// registerCache(SyncType.QUEST_CATEGORY, SyncControllerOld::questCategoriesNBT);
+// registerCache(SyncType.WORKBENCH_RECIPES, SyncControllerOld::workbenchNBT);
+// registerCache(SyncType.CARPENTRY_RECIPES, SyncControllerOld::carpentryNBT);
+// registerCache(SyncType.ANVIL_RECIPES, SyncControllerOld::anvilNBT);
+// registerCache(SyncType.CUSTOM_EFFECTS, SyncControllerOld::customEffectsNBT);
+// registerCache(SyncType.MAGIC, SyncControllerOld::magicsNBT);
+// registerCache(SyncType.MAGIC_CYCLE, SyncControllerOld::magicCyclesNBT);
+// registerCache(SyncType.CUSTOM_ABILITY, SyncControllerOld::customAbilitiesNBT);
+// registerCache(SyncType.CHAINED_ABILITY, SyncControllerOld::chainedAbilitiesNBT);
+// }
+//
+// public static void syncPlayer(EntityPlayerMP player) {
+// SyncControllerOld.syncPlayerInternal(player, true);
+// }
+//
+// private static void syncPlayerInternal(EntityPlayerMP player, boolean includePostPackets) {
+// PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
+//
+// for (SyncType type : LOGIN_SYNC_TYPES) {
+// SyncCacheEntry entry = cacheEntries.get(type);
+// if (entry == null) {
+// continue;
+// }
+//
+// int currentRevision = entry.getRevisionValue();
+// int lastRevision = state.getRevision(type);
+// if (lastRevision == currentRevision) {
+// continue;
+// }
+//
+// CachedSyncPayload payload = entry.getPayload(type);
+// if (payload == null) {
+// continue;
+// }
+//
+// if (lastRevision != payload.getRevision()) {
+// debug("Sending %s data to %s", type, player.getCommandSenderName());
+// PacketHandler.Instance.sendToPlayer(new SyncPacket(type, payload), player);
+// state.updateRevision(type, payload.getRevision());
+// }
+// }
+//
+// if (includePostPackets) {
+// sendPostLoginPackets(player);
+// }
+// }
+//
+// public static void beginLogin(EntityPlayerMP player) {
+// playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
+// PacketHandler.Instance.sendToPlayer(
+// new LoginPacket(getServerCacheKey(), getServerRevisionSnapshot()),
+// player
+// );
+// }
+//
+// public static void handleClientRevisionReport(
+// EntityPlayerMP player,
+// String serverKey,
+// String previousServerKey,
+// Map clientRevisions
+// ) {
+// String currentServerKey = getServerCacheKey();
+// PlayerSyncState state = playerSyncState.computeIfAbsent(player.getUniqueID(), PlayerSyncState::new);
+//
+// if (!currentServerKey.equals(serverKey)) {
+// state.reset();
+// syncPlayer(player);
+// return;
+// }
+//
+// if (!currentServerKey.isEmpty()) {
+// if (previousServerKey == null || !currentServerKey.equals(previousServerKey)) {
+// state.reset();
+// syncPlayer(player);
+// return;
+// }
+// }
+//
+// if (clientRevisions == null || clientRevisions.isEmpty()) {
+// debug(
+// "Client %s reported no cached revisions; forcing full sync",
+// player.getCommandSenderName()
+// );
+// state.reset();
+// } else {
+// state.applyHandshake(clientRevisions);
+// }
+//
+// syncPlayer(player);
+// }
+//
+// private static void sendPostLoginPackets(EntityPlayerMP player) {
+// DBCAddon.instance.syncPlayer(player);
+// syncPlayerData(player, false);
+// PartyInfoPacket.sendPartyData(player);
+// ProfileSharedQuestPacket.sendToPlayer(player);
+//
+// // Sync skin overlays after full handshake to ensure the client is ready.
+// // Overlays are not part of getSyncNBTFull(), and packets sent during
+// // PlayerLoggedInEvent can arrive before the client entity exists.
+// PlayerData data = PlayerData.get(player);
+// if (data != null) {
+// data.skinOverlays.updateClient();
+// }
+// }
+//
+// private static Map getServerRevisionSnapshot() {
+// Map snapshot = new LinkedHashMap<>();
+// for (SyncType type : LOGIN_SYNC_TYPES) {
+// SyncCacheEntry entry = cacheEntries.get(type);
+// if (entry != null) {
+// snapshot.put(type, entry.getRevisionValue());
+// }
+// }
+// return snapshot;
+// }
+//
+// private static final String SERVER_IDENTITY_KEY = UUID.randomUUID().toString();
+//
+// private static String getServerCacheKey() {
+// MinecraftServer server = MinecraftServer.getServer();
+// if (server == null) {
+// return "";
+// }
+//
+// if (!server.isDedicatedServer()) {
+// return "";
+// }
+//
+// return SERVER_IDENTITY_KEY;
+// }
+//
+// public static int getCurrentRevision(SyncType type) {
+// SyncCacheEntry entry = cacheEntries.get(type);
+// return entry == null ? -1 : entry.getRevisionValue();
+// }
+//
+// public static NBTTagCompound workbenchNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound carpentryNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound anvilNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound factionsNBT() {
+// NBTTagList list = new NBTTagList();
+// NBTTagCompound compound = new NBTTagCompound();
+// for (Faction faction : FactionController.getInstance().factions.values()) {
+// NBTTagCompound factioNBT = new NBTTagCompound();
+// faction.writeNBT(factioNBT);
+// list.appendTag(factioNBT);
+// }
+// compound.setTag("Factions", list);
+// return compound;
+// }
+//
+// public static NBTTagCompound dialogCategoriesNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound questCategoriesNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound customEffectsNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound magicsNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound magicCyclesNBT() {
+// 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;
+// }
+//
+// public static NBTTagCompound customAbilitiesNBT() {
+// NBTTagList list = new NBTTagList();
+// NBTTagCompound compound = new NBTTagCompound();
+// for (Map.Entry 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;
+// }
+//
+// public static void syncAllCustomAbilities() {
+// CachedSyncPayload payload = rebuildNow(SyncType.CUSTOM_ABILITY);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CUSTOM_ABILITY, payload));
+// updateAllPlayerRevisions(SyncType.CUSTOM_ABILITY, payload.getRevision());
+// }
+//
+// public static NBTTagCompound chainedAbilitiesNBT() {
+// NBTTagList list = new NBTTagList();
+// NBTTagCompound compound = new NBTTagCompound();
+// for (Map.Entry 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;
+// }
+//
+// public static void syncAllChainedAbilities() {
+// CachedSyncPayload payload = rebuildNow(SyncType.CHAINED_ABILITY);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CHAINED_ABILITY, payload));
+// updateAllPlayerRevisions(SyncType.CHAINED_ABILITY, payload.getRevision());
+// }
+//
+// public static void syncPlayerData(EntityPlayerMP player, boolean update) {
+// PlayerData data = PlayerData.get(player);
+// if (data != null) {
+// if (update) {
+// PacketHandler.Instance.sendToPlayer(new SyncPacket(
+// SyncType.PLAYERDATA,
+// EnumSyncAction.UPDATE,
+// -1,
+// data.getSyncNBT())
+// , player);
+// } else {
+// PacketHandler.Instance.sendToPlayer(new SyncPacket(
+// SyncType.PLAYERDATA,
+// EnumSyncAction.RELOAD,
+// -1,
+// data.getSyncNBTFull()), player);
+// }
+// }
+// }
+//
+// public static void syncRemove(SyncType syncType, int id) {
+// Map revisions = invalidateCaches(syncType);
+// int revision = revisions.getOrDefault(syncType, getCurrentRevision(syncType));
+// PacketHandler.Instance.sendToAll(new SyncPacket(
+// syncType,
+// EnumSyncAction.REMOVE,
+// id,
+// revision,
+// new NBTTagCompound()
+// ));
+// updateAllPlayerRevisions(revisions);
+// }
+//
+// public static void syncAllDialogs() {
+// CachedSyncPayload payload = rebuildNow(SyncType.DIALOG_CATEGORY);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.DIALOG_CATEGORY, payload));
+// updateAllPlayerRevisions(SyncType.DIALOG_CATEGORY, payload.getRevision());
+// }
+//
+// public static void syncAllQuests() {
+// CachedSyncPayload payload = rebuildNow(SyncType.QUEST_CATEGORY);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.QUEST_CATEGORY, payload));
+// updateAllPlayerRevisions(SyncType.QUEST_CATEGORY, payload.getRevision());
+// }
+//
+// public static void syncAllWorkbenchRecipes() {
+// CachedSyncPayload payload = rebuildNow(SyncType.WORKBENCH_RECIPES);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.WORKBENCH_RECIPES, payload));
+// updateAllPlayerRevisions(SyncType.WORKBENCH_RECIPES, payload.getRevision());
+// }
+//
+// public static void syncAllCarpentryRecipes() {
+// CachedSyncPayload payload = rebuildNow(SyncType.CARPENTRY_RECIPES);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CARPENTRY_RECIPES, payload));
+// updateAllPlayerRevisions(SyncType.CARPENTRY_RECIPES, payload.getRevision());
+// }
+//
+// public static void syncAllAnvilRecipes() {
+// CachedSyncPayload payload = rebuildNow(SyncType.ANVIL_RECIPES);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.ANVIL_RECIPES, payload));
+// updateAllPlayerRevisions(SyncType.ANVIL_RECIPES, payload.getRevision());
+// }
+//
+// public static void syncAllCustomEffects() {
+// CachedSyncPayload payload = rebuildNow(SyncType.CUSTOM_EFFECTS);
+// if (payload == null) {
+// return;
+// }
+// PacketHandler.Instance.sendToAll(new SyncPacket(SyncType.CUSTOM_EFFECTS, payload));
+// updateAllPlayerRevisions(SyncType.CUSTOM_EFFECTS, payload.getRevision());
+// }
+//
+// @SideOnly(Side.CLIENT)
+// public static void clientSync(SyncType syncType, int revision, NBTTagCompound fullCompound) {
+// if (syncType == SyncType.FACTION) {
+// 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();
+// } else if (syncType == SyncType.DIALOG_CATEGORY) {
+// 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 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();
+// } else if (syncType == SyncType.QUEST_CATEGORY) {
+// 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 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();
+// } else if (syncType == SyncType.PLAYERDATA) {
+// ClientCacheHandler.playerData.setSyncNBTFull(fullCompound);
+// } else if (syncType == SyncType.MAGIC) {
+// 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();
+// } else if (syncType == SyncType.MAGIC_CYCLE) {
+// 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();
+// } else if (syncType == SyncType.WORKBENCH_RECIPES) {
+// 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();
+// } else if (syncType == SyncType.CARPENTRY_RECIPES) {
+// 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();
+// } else if (syncType == SyncType.ANVIL_RECIPES) {
+// 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();
+// } else if (syncType == SyncType.CUSTOM_EFFECTS) {
+// 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();
+// } else if (syncType == SyncType.CUSTOM_ABILITY) {
+// NBTTagList list = fullCompound.getTagList("Data", 10);
+// LinkedHashMap 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);
+// } else if (syncType == SyncType.CHAINED_ABILITY) {
+// NBTTagList list = fullCompound.getTagList("Data", 10);
+// LinkedHashMap 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);
+// }
+//
+// ClientCacheHandler.updateClientRevision(syncType, revision);
+// }
+//
+// @SideOnly(Side.CLIENT)
+// public static void clientUpdate(SyncType syncType, int category_id, int revision, NBTTagCompound compound) {
+// if (syncType == SyncType.FACTION) {
+// Faction faction = new Faction();
+// faction.readNBT(compound);
+// FactionController.getInstance().factions.put(faction.id, faction);
+// } else if (syncType == SyncType.DIALOG) {
+// DialogCategory category = DialogController.Instance.categories.get(category_id);
+// Dialog dialog = new Dialog();
+// dialog.category = category;
+// dialog.readNBT(compound);
+// DialogController.Instance.dialogs.put(dialog.id, dialog);
+// category.dialogs.put(dialog.id, dialog);
+// } else if (syncType == SyncType.QUEST) {
+// QuestCategory category = QuestController.Instance.categories.get(category_id);
+// Quest quest = new Quest();
+// quest.category = category;
+// quest.readNBT(compound);
+// QuestController.Instance.quests.put(quest.id, quest);
+// category.quests.put(quest.id, quest);
+// } else if (syncType == SyncType.QUEST_CATEGORY) {
+// 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);
+// } else if (syncType == SyncType.DIALOG_CATEGORY) {
+// 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);
+// } else if (syncType == SyncType.MAGIC_CYCLE) {
+// MagicCycle cycle = new MagicCycle();
+// cycle.readNBT(compound);
+// MagicController.getInstance().cycles.put(cycle.id, cycle);
+// } else if (syncType == SyncType.MAGIC) {
+// Magic magic = new Magic();
+// magic.readNBT(compound);
+// MagicController.getInstance().magics.put(magic.id, magic);
+// } else if (syncType == SyncType.PLAYERDATA) {
+// ClientCacheHandler.playerData.setSyncNBT(compound);
+// } else if (syncType == SyncType.CUSTOM_EFFECTS) {
+// CustomEffect effect = new CustomEffect();
+// effect.readFromNBT(compound);
+// ClientCacheHandler.getImageData(effect.icon);
+//
+// CustomEffectController.Instance.getCustomEffects().put(effect.id, effect);
+// }
+//
+// ClientCacheHandler.updateClientRevision(syncType, revision);
+// }
+//
+// public static void syncUpdate(SyncType type, int cat, NBTTagCompound compound) {
+// Map revisions = invalidateCaches(type);
+// int revision = revisions.getOrDefault(type, getCurrentRevision(type));
+// PacketHandler.Instance.sendToAll(new SyncPacket(
+// type,
+// EnumSyncAction.UPDATE,
+// cat,
+// revision,
+// compound
+// ));
+// updateAllPlayerRevisions(revisions);
+// }
+//
+//
+// public static NBTTagCompound updateQuestCat(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;
+// }
+//
+// public static NBTTagCompound updateDialogCat(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;
+// }
+//
+// @SideOnly(Side.CLIENT)
+// public static void clientSyncRemove(SyncType syncType, int id, int revision) {
+// if (syncType == SyncType.FACTION) {
+// FactionController.getInstance().factions.remove(id);
+// } else if (syncType == SyncType.DIALOG) {
+// Dialog dialog = DialogController.Instance.dialogs.remove(id);
+// if (dialog != null) {
+// dialog.category.dialogs.remove(id);
+// }
+// } else if (syncType == SyncType.DIALOG_CATEGORY) {
+// DialogCategory dialogCategory = DialogController.Instance.categories.remove(id);
+// if (dialogCategory != null) {
+// DialogController.Instance.dialogs.keySet().removeAll(dialogCategory.dialogs.keySet());
+// }
+// } else if (syncType == SyncType.QUEST) {
+// Quest quest = QuestController.Instance.quests.remove(id);
+// if (quest != null) {
+// quest.category.quests.remove(id);
+// }
+// } else if (syncType == SyncType.QUEST_CATEGORY) {
+// QuestCategory questCategory = QuestController.Instance.categories.remove(id);
+// if (questCategory != null) {
+// QuestController.Instance.quests.keySet().removeAll(questCategory.quests.keySet());
+// }
+// } else if (syncType == SyncType.MAGIC) {
+// for (MagicCycle cycle : MagicController.getInstance().cycles.values()) {
+// cycle.associations.remove(id);
+// }
+// MagicController.getInstance().cycles.remove(id);
+// } else if (syncType == SyncType.MAGIC_CYCLE) {
+// MagicController.getInstance().cycles.remove(id);
+// } else if (syncType == SyncType.CUSTOM_EFFECTS) {
+// CustomEffectController.Instance.getCustomEffects().remove(id);
+// }
+//
+// ClientCacheHandler.updateClientRevision(syncType, revision);
+// }
+//
+// public static void syncEffects(EntityPlayerMP playerMP) {
+// ConcurrentHashMap 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);
+// }
+//
+// /**
+// * 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);
+// }
+//
+// @SideOnly(Side.CLIENT)
+// public static void clientSyncEffects(NBTTagCompound compound) {
+// PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer);
+// if (playerData != null) {
+// playerData.setPlayerEffects(compound);
+// }
+// }
+//
+// private static void registerCache(SyncType type, Supplier supplier) {
+// cacheEntries.put(type, new SyncCacheEntry(supplier));
+// }
+//
+// private static CachedSyncPayload rebuildNow(SyncType type) {
+// SyncCacheEntry entry = cacheEntries.get(type);
+// if (entry == null) {
+// return null;
+// }
+// entry.invalidate();
+// return entry.getPayload(type);
+// }
+//
+// public static Map invalidateCaches(SyncType type) {
+// Set targets = getInvalidationTargets(type);
+// Map revisions = new LinkedHashMap<>();
+// for (SyncType target : targets) {
+// SyncCacheEntry entry = cacheEntries.get(target);
+// if (entry != null) {
+// int newRevision = entry.invalidate();
+// revisions.put(target, newRevision);
+// }
+// }
+// return revisions;
+// }
+//
+// private static Set