"));
+ 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/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/RenderEnergyBeam.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java
new file mode 100644
index 000000000..c870f6a07
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyBeam.java
@@ -0,0 +1,597 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.entity.EntityAbilityBeam;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.entity.Entity;
+import net.minecraft.util.Vec3;
+import org.lwjgl.opengl.GL11;
+
+import java.util.ArrayList;
+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 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, proximityAlpha);
+ restoreRenderState();
+ return;
+ }
+
+ // Get trail points (these are RELATIVE to origin)
+ List trail = beam.getTrailPoints();
+ if (trail.isEmpty()) {
+ restoreRenderState();
+ return;
+ }
+
+ // Get interpolated head offset
+ 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;
+
+ // Get beam properties
+ float beamWidth = beam.getBeamWidth();
+ float headSize = beam.getHeadSize();
+ int innerColor = beam.getInnerColor();
+ int outerColor = beam.getOuterColor();
+ float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
+
+ // Render everything relative to origin position
+ GL11.glPushMatrix();
+ GL11.glTranslated(renderOriginX, renderOriginY, renderOriginZ);
+
+ // Calculate head distance from origin (for overlap check)
+ double headDistFromOrigin = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ);
+
+ // Render tail orb at origin (0,0,0) - only in anchored mode
+ // Don't render if head is too close to origin (would cause overlap/extra orb appearance)
+ if (beam.shouldRenderTailOrb() && headDistFromOrigin > headSize * 0.5) {
+ renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, beam.getInnerAlpha() * proximityAlpha);
+ }
+
+ float innerAlpha = beam.getInnerAlpha() * proximityAlpha;
+
+ // Render trail segments with smooth connections (with fading for non-anchored)
+ 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 head at interpolated offset position
+ renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks);
+
+ GL11.glPopMatrix();
+
+ restoreRenderState();
+ }
+
+ /**
+ * 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 proximityAlpha) {
+ float headSize = beam.getHeadSize();
+ float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks);
+ float size = headSize * chargeProgress;
+
+ if (size <= 0.01f) return;
+
+ int innerColor = beam.getInnerColor();
+ int outerColor = beam.getOuterColor();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Pulsing effect
+ float pulseTime = beam.ticksExisted + partialTicks;
+ float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f;
+ float scale = size * (1.0f + scaleModifier);
+
+ // Render lightning during charging if enabled
+ if (beam.hasLightningEffect()) {
+ renderAttachedLightning(beam, 0.6f * 0.5f, scale);
+ }
+
+ GL11.glPushMatrix();
+ GL11.glScalef(scale, scale, scale);
+
+ // Inner scale defines the core size
+ float innerScale = 0.6f;
+
+ // Render outer glow only if enabled
+ if (beam.isOuterColorEnabled()) {
+ float outerScale = innerScale + beam.getOuterColorWidth();
+ float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
+ GL11.glDepthMask(false);
+ GL11.glPushMatrix();
+ GL11.glScalef(outerScale, outerScale, outerScale);
+ renderCube(outerColor, outerAlpha, 0.5f);
+ GL11.glPopMatrix();
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner core
+ GL11.glScalef(innerScale, innerScale, innerScale);
+ renderCube(innerColor, beam.getInnerAlpha() * proximityAlpha, 0.5f);
+
+ GL11.glPopMatrix();
+ GL11.glPopMatrix();
+ }
+
+ /**
+ * 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, float innerAlpha) {
+ GL11.glPushMatrix();
+ // Already at origin (0,0,0)
+
+ // Inner scale defines the core size
+ float innerScale = 0.6f;
+
+ // Render outer glow only if enabled
+ // outerColorWidth is an additive offset from inner size
+ if (outerColorEnabled) {
+ float outerScale = innerScale + outerColorWidth;
+ GL11.glDepthMask(false);
+ GL11.glPushMatrix();
+ GL11.glScalef(size * outerScale, size * outerScale, size * outerScale);
+ renderCube(outerColor, outerAlpha, 0.5f);
+ GL11.glPopMatrix();
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner core (solid)
+ GL11.glPushMatrix();
+ GL11.glScalef(size * innerScale, size * innerScale, size * innerScale);
+ renderCube(innerColor, innerAlpha, 0.5f);
+ GL11.glPopMatrix();
+
+ GL11.glPopMatrix();
+ }
+
+ /**
+ * Render the beam trail with smooth connections between segments.
+ * 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, float innerAlpha) {
+ if (trail.size() < 2) return;
+
+ int trailSize = trail.size();
+
+ // Pre-compute perpendicular frames at each point
+ // At connection points, average the perpendiculars for smooth transitions
+ List perpFrames = computePerpendiculars(trail);
+
+ // Inner scale defines the core width
+ float innerScale = 0.6f;
+ float innerWidth = width * innerScale;
+
+ // Render outer glow trail (wider, translucent) - only if enabled
+ // outerColorWidth is an additive offset from inner width
+ if (outerColorEnabled) {
+ float outerWidth = innerWidth + outerColorWidth * width;
+ GL11.glDepthMask(false);
+ renderTrailTube(trail, perpFrames, outerWidth, outerColor, 0.3f, true);
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner core trail
+ renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false);
+ }
+
+ /**
+ * Render trail with fading effect (comet style) for non-anchored beams.
+ * 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, float innerAlpha) {
+ if (trail.size() < 2) return;
+
+ List ages = beam.getTrailPointAges();
+ int fadeTime = beam.getTrailFadeTime();
+
+ // Pre-compute perpendicular frames
+ List perpFrames = computePerpendiculars(trail);
+
+ // Inner scale defines the core width
+ float innerScale = 0.6f;
+ float innerWidth = width * innerScale;
+
+ // Render outer glow trail with fading
+ if (outerColorEnabled) {
+ float outerWidth = innerWidth + outerColorWidth * width;
+ GL11.glDepthMask(false);
+ renderFadingTrailTube(trail, perpFrames, ages, fadeTime, outerWidth, outerColor, 0.3f);
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner core trail with fading
+ 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) {
+ float[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+ float halfWidth = width * 0.5f;
+ int size = trail.size();
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+
+ for (int i = 0; i < size - 1; i++) {
+ Vec3 p1 = trail.get(i);
+ Vec3 p2 = trail.get(i + 1);
+ double[] frame1 = perpFrames.get(i);
+ double[] frame2 = perpFrames.get(i + 1);
+
+ // 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 = 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;
+
+ // Skip fully faded segments
+ if (alpha1 <= 0.01f && alpha2 <= 0.01f) continue;
+
+ // Calculate 4 corners at start
+ double s1x = p1.xCoord - frame1[0] * halfWidth - frame1[3] * halfWidth;
+ double s1y = p1.yCoord - frame1[1] * halfWidth - frame1[4] * halfWidth;
+ double s1z = p1.zCoord - frame1[2] * halfWidth - frame1[5] * halfWidth;
+
+ double s2x = p1.xCoord + frame1[0] * halfWidth - frame1[3] * halfWidth;
+ double s2y = p1.yCoord + frame1[1] * halfWidth - frame1[4] * halfWidth;
+ double s2z = p1.zCoord + frame1[2] * halfWidth - frame1[5] * halfWidth;
+
+ double s3x = p1.xCoord + frame1[0] * halfWidth + frame1[3] * halfWidth;
+ double s3y = p1.yCoord + frame1[1] * halfWidth + frame1[4] * halfWidth;
+ double s3z = p1.zCoord + frame1[2] * halfWidth + frame1[5] * halfWidth;
+
+ double s4x = p1.xCoord - frame1[0] * halfWidth + frame1[3] * halfWidth;
+ double s4y = p1.yCoord - frame1[1] * halfWidth + frame1[4] * halfWidth;
+ double s4z = p1.zCoord - frame1[2] * halfWidth + frame1[5] * halfWidth;
+
+ // Calculate 4 corners at end
+ double e1x = p2.xCoord - frame2[0] * halfWidth - frame2[3] * halfWidth;
+ double e1y = p2.yCoord - frame2[1] * halfWidth - frame2[4] * halfWidth;
+ double e1z = p2.zCoord - frame2[2] * halfWidth - frame2[5] * halfWidth;
+
+ double e2x = p2.xCoord + frame2[0] * halfWidth - frame2[3] * halfWidth;
+ double e2y = p2.yCoord + frame2[1] * halfWidth - frame2[4] * halfWidth;
+ double e2z = p2.zCoord + frame2[2] * halfWidth - frame2[5] * halfWidth;
+
+ double e3x = p2.xCoord + frame2[0] * halfWidth + frame2[3] * halfWidth;
+ double e3y = p2.yCoord + frame2[1] * halfWidth + frame2[4] * halfWidth;
+ double e3z = p2.zCoord + frame2[2] * halfWidth + frame2[5] * halfWidth;
+
+ double e4x = p2.xCoord - frame2[0] * halfWidth + frame2[3] * halfWidth;
+ double e4y = p2.yCoord - frame2[1] * halfWidth + frame2[4] * halfWidth;
+ double e4z = p2.zCoord - frame2[2] * halfWidth + frame2[5] * halfWidth;
+
+ // Bottom face
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s1x, s1y, s1z);
+ tess.addVertex(s2x, s2y, s2z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e2x, e2y, e2z);
+ tess.addVertex(e1x, e1y, e1z);
+
+ // Top face
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s4x, s4y, s4z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s3x, s3y, s3z);
+
+ // Left face
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s1x, s1y, s1z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e1x, e1y, e1z);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s4x, s4y, s4z);
+
+ // Right face
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s2x, s2y, s2z);
+ tess.addVertex(s3x, s3y, s3z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(e2x, e2y, e2z);
+ }
+
+ tess.draw();
+ }
+
+ /**
+ * Compute perpendicular frames for each point in the trail.
+ * At interior points, average the perpendiculars from both directions for smooth curves.
+ * Returns list of [horzX, horzY, horzZ, vertX, vertY, vertZ] for each point.
+ */
+ private List computePerpendiculars(List trail) {
+ List frames = new ArrayList<>();
+ int size = trail.size();
+
+ for (int i = 0; i < size; i++) {
+ double[] frame = new double[6];
+
+ // Calculate direction at this point
+ double dx, dy, dz;
+ if (i == 0) {
+ // First point - use direction to next
+ Vec3 p1 = trail.get(0);
+ Vec3 p2 = trail.get(1);
+ dx = p2.xCoord - p1.xCoord;
+ dy = p2.yCoord - p1.yCoord;
+ dz = p2.zCoord - p1.zCoord;
+ } else if (i == size - 1) {
+ // Last point - use direction from previous
+ Vec3 p1 = trail.get(size - 2);
+ Vec3 p2 = trail.get(size - 1);
+ dx = p2.xCoord - p1.xCoord;
+ dy = p2.yCoord - p1.yCoord;
+ dz = p2.zCoord - p1.zCoord;
+ } else {
+ // Interior point - average directions
+ Vec3 p0 = trail.get(i - 1);
+ Vec3 p1 = trail.get(i);
+ Vec3 p2 = trail.get(i + 1);
+ double dx1 = p1.xCoord - p0.xCoord;
+ double dy1 = p1.yCoord - p0.yCoord;
+ double dz1 = p1.zCoord - p0.zCoord;
+ double dx2 = p2.xCoord - p1.xCoord;
+ double dy2 = p2.yCoord - p1.yCoord;
+ double dz2 = p2.zCoord - p1.zCoord;
+ // Average the directions
+ dx = (dx1 + dx2) * 0.5;
+ dy = (dy1 + dy2) * 0.5;
+ dz = (dz1 + dz2) * 0.5;
+ }
+
+ // Normalize direction
+ double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
+ if (len > 0.001) {
+ dx /= len;
+ dy /= len;
+ dz /= len;
+ } else {
+ 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;
+ }
+
+ // Cross product for horizontal perpendicular
+ double horzX = dy * upZ - dz * upY;
+ double horzY = dz * upX - dx * upZ;
+ double horzZ = dx * upY - dy * upX;
+ double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ);
+ if (horzLen > 0) {
+ horzX /= horzLen;
+ horzY /= horzLen;
+ horzZ /= horzLen;
+ }
+
+ // Cross product for vertical perpendicular
+ double vertX = dy * horzZ - dz * horzY;
+ 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;
+ frames.add(frame);
+ }
+
+ return frames;
+ }
+
+ /**
+ * 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[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+ float halfWidth = width * 0.5f;
+ int size = trail.size();
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+
+ for (int i = 0; i < size - 1; i++) {
+ Vec3 p1 = trail.get(i);
+ Vec3 p2 = trail.get(i + 1);
+ double[] frame1 = perpFrames.get(i);
+ double[] frame2 = perpFrames.get(i + 1);
+
+ // Calculate alpha based on position (fade from start or constant)
+ float alpha1, alpha2;
+ if (fadeFromStart) {
+ float progress1 = (float) i / size;
+ float progress2 = (float) (i + 1) / size;
+ alpha1 = baseAlpha * progress1;
+ alpha2 = baseAlpha * progress2;
+ } else {
+ alpha1 = baseAlpha;
+ alpha2 = baseAlpha;
+ }
+
+ // Calculate 4 corners at start
+ double s1x = p1.xCoord - frame1[0] * halfWidth - frame1[3] * halfWidth;
+ double s1y = p1.yCoord - frame1[1] * halfWidth - frame1[4] * halfWidth;
+ double s1z = p1.zCoord - frame1[2] * halfWidth - frame1[5] * halfWidth;
+
+ double s2x = p1.xCoord + frame1[0] * halfWidth - frame1[3] * halfWidth;
+ double s2y = p1.yCoord + frame1[1] * halfWidth - frame1[4] * halfWidth;
+ double s2z = p1.zCoord + frame1[2] * halfWidth - frame1[5] * halfWidth;
+
+ double s3x = p1.xCoord + frame1[0] * halfWidth + frame1[3] * halfWidth;
+ double s3y = p1.yCoord + frame1[1] * halfWidth + frame1[4] * halfWidth;
+ double s3z = p1.zCoord + frame1[2] * halfWidth + frame1[5] * halfWidth;
+
+ double s4x = p1.xCoord - frame1[0] * halfWidth + frame1[3] * halfWidth;
+ double s4y = p1.yCoord - frame1[1] * halfWidth + frame1[4] * halfWidth;
+ double s4z = p1.zCoord - frame1[2] * halfWidth + frame1[5] * halfWidth;
+
+ // Calculate 4 corners at end
+ double e1x = p2.xCoord - frame2[0] * halfWidth - frame2[3] * halfWidth;
+ double e1y = p2.yCoord - frame2[1] * halfWidth - frame2[4] * halfWidth;
+ double e1z = p2.zCoord - frame2[2] * halfWidth - frame2[5] * halfWidth;
+
+ double e2x = p2.xCoord + frame2[0] * halfWidth - frame2[3] * halfWidth;
+ double e2y = p2.yCoord + frame2[1] * halfWidth - frame2[4] * halfWidth;
+ double e2z = p2.zCoord + frame2[2] * halfWidth - frame2[5] * halfWidth;
+
+ double e3x = p2.xCoord + frame2[0] * halfWidth + frame2[3] * halfWidth;
+ double e3y = p2.yCoord + frame2[1] * halfWidth + frame2[4] * halfWidth;
+ double e3z = p2.zCoord + frame2[2] * halfWidth + frame2[5] * halfWidth;
+
+ double e4x = p2.xCoord - frame2[0] * halfWidth + frame2[3] * halfWidth;
+ double e4y = p2.yCoord - frame2[1] * halfWidth + frame2[4] * halfWidth;
+ double e4z = p2.zCoord - frame2[2] * halfWidth + frame2[5] * halfWidth;
+
+ // Bottom face (s1-s2-e2-e1)
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s1x, s1y, s1z);
+ tess.addVertex(s2x, s2y, s2z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e2x, e2y, e2z);
+ tess.addVertex(e1x, e1y, e1z);
+
+ // Top face (s4-e4-e3-s3)
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s4x, s4y, s4z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s3x, s3y, s3z);
+
+ // Left face (s1-e1-e4-s4)
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s1x, s1y, s1z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e1x, e1y, e1z);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s4x, s4y, s4z);
+
+ // Right face (s2-s3-e3-e2)
+ tess.setColorRGBA_F(r, g, b, alpha1);
+ tess.addVertex(s2x, s2y, s2z);
+ tess.addVertex(s3x, s3y, s3z);
+ tess.setColorRGBA_F(r, g, b, alpha2);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(e2x, e2y, e2z);
+ }
+
+ tess.draw();
+ }
+
+ /**
+ * Render the beam head as a glowing cube.
+ * 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 innerAlpha, float partialTicks) {
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Pulsing effect
+ float pulseTime = beam.ticksExisted + partialTicks;
+ float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.1f;
+ float scale = size * (1.0f + scaleModifier);
+
+ // Render lightning BEFORE rotation so it crackles in all directions (only on head)
+ if (beam.hasLightningEffect()) {
+ renderAttachedLightning(beam, 0.6f * 0.5f, scale);
+ }
+
+ // Rotation
+ GL11.glRotatef(beam.getInterpolatedRotationX(partialTicks), 1.0f, 0.0f, 0.0f);
+ GL11.glRotatef(beam.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
+ GL11.glRotatef(beam.getInterpolatedRotationZ(partialTicks), 0.0f, 0.0f, 1.0f);
+
+ GL11.glPushMatrix();
+ GL11.glScalef(scale, scale, scale);
+
+ // Inner scale defines the core size
+ float innerScale = 0.6f;
+
+ // Render outer glow only if enabled
+ // outerColorWidth is an additive offset from inner size
+ if (beam.isOuterColorEnabled()) {
+ float outerScale = innerScale + beam.getOuterColorWidth();
+ GL11.glDepthMask(false);
+ GL11.glPushMatrix();
+ GL11.glScalef(outerScale, outerScale, outerScale);
+ renderCube(outerColor, outerAlpha, 0.5f);
+ GL11.glPopMatrix();
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner core
+ GL11.glScalef(innerScale, innerScale, innerScale);
+ renderCube(innerColor, innerAlpha, 0.5f);
+
+ GL11.glPopMatrix();
+ GL11.glPopMatrix();
+ }
+
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java
new file mode 100644
index 000000000..eb4d9f21c
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyDisc.java
@@ -0,0 +1,181 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+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 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();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Get interpolated values
+ float size = disc.getInterpolatedSize(partialTicks);
+ float radius = disc.getDiscRadius() * size;
+ float thickness = disc.getDiscThickness() * size;
+
+ // Subtle pulsing effect
+ float pulseTime = entity.ticksExisted + partialTicks;
+ float scaleModifier = (float) Math.sin(pulseTime * 0.1f) * 0.03f;
+ float scale = 1.0f + scaleModifier;
+
+ // Render lightning BEFORE rotation so it crackles in all directions
+ if (disc.hasLightningEffect()) {
+ renderAttachedLightning(disc, 0.6f * 0.5f, radius * scale);
+ }
+
+ GL11.glPushMatrix();
+ GL11.glScalef(scale, scale, scale);
+
+ if (disc.isVertical()) {
+ // Vertical mode: thin edge faces direction of travel (like a saw blade)
+ // 1. Spin in local space (Y-axis)
+ // 2. Tilt 90° to stand up (X-axis)
+ // 3. Orient to face travel direction (Y-axis world yaw)
+ GL11.glRotatef(disc.getTravelYaw(), 0.0f, 1.0f, 0.0f);
+ GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
+ }
+
+ 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() * proximityAlpha, radius * outerScale, thickness);
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner square (solid)
+ renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha() * proximityAlpha, radius * innerScale, thickness * 1.2f);
+
+ GL11.glPopMatrix();
+ GL11.glPopMatrix();
+
+ restoreRenderState();
+ }
+
+ /**
+ * Render a flat square (thin cube) centered at origin.
+ * The square lies flat on the XZ plane with thin Y height.
+ */
+ private void renderFlatSquare(int color, float alpha, float halfSize, float thickness) {
+ float halfThick = thickness * 0.5f;
+
+ // Render as a thin cube
+ renderCubeCustom(color, alpha, halfSize, halfThick, halfSize);
+ }
+
+ /**
+ * Render a cube with custom dimensions.
+ */
+ private void renderCubeCustom(int color, float alpha, float halfX, float halfY, float halfZ) {
+ float[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+
+ net.minecraft.client.renderer.Tessellator tess = net.minecraft.client.renderer.Tessellator.instance;
+
+ // Top face (y+)
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(0, 1, 0);
+ tess.addVertex(-halfX, halfY, halfZ);
+ tess.addVertex(halfX, halfY, halfZ);
+ tess.addVertex(halfX, halfY, -halfZ);
+ tess.addVertex(-halfX, halfY, -halfZ);
+ tess.draw();
+
+ // Bottom face (y-)
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(0, -1, 0);
+ tess.addVertex(-halfX, -halfY, -halfZ);
+ tess.addVertex(halfX, -halfY, -halfZ);
+ tess.addVertex(halfX, -halfY, halfZ);
+ tess.addVertex(-halfX, -halfY, halfZ);
+ tess.draw();
+
+ // Front face (z+)
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(0, 0, 1);
+ tess.addVertex(-halfX, -halfY, halfZ);
+ tess.addVertex(halfX, -halfY, halfZ);
+ tess.addVertex(halfX, halfY, halfZ);
+ tess.addVertex(-halfX, halfY, halfZ);
+ tess.draw();
+
+ // Back face (z-)
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(0, 0, -1);
+ tess.addVertex(halfX, -halfY, -halfZ);
+ tess.addVertex(-halfX, -halfY, -halfZ);
+ tess.addVertex(-halfX, halfY, -halfZ);
+ tess.addVertex(halfX, halfY, -halfZ);
+ tess.draw();
+
+ // Right face (x+)
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(1, 0, 0);
+ tess.addVertex(halfX, -halfY, halfZ);
+ tess.addVertex(halfX, -halfY, -halfZ);
+ tess.addVertex(halfX, halfY, -halfZ);
+ tess.addVertex(halfX, halfY, halfZ);
+ tess.draw();
+
+ // Left face (x-)
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+ tess.setNormal(-1, 0, 0);
+ tess.addVertex(-halfX, -halfY, -halfZ);
+ tess.addVertex(-halfX, -halfY, halfZ);
+ tess.addVertex(-halfX, halfY, halfZ);
+ tess.addVertex(-halfX, halfY, -halfZ);
+ tess.draw();
+ }
+}
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/RenderEnergyLaser.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java
new file mode 100644
index 000000000..c2cfe716a
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyLaser.java
@@ -0,0 +1,350 @@
+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.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 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) {
+ EntityAbilityLaser laser = (EntityAbilityLaser) entity;
+
+ 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, proximityAlpha);
+ restoreRenderState();
+ return;
+ }
+
+ // 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.getLaserWidth();
+ float alpha = 1.0f;
+
+ // Calculate render offset (entity position is used as reference)
+ double offsetX = x - laser.posX;
+ double offsetY = y - laser.posY;
+ double offsetZ = z - laser.posZ;
+
+ // Render start relative to camera
+ double renderStartX = startX + offsetX;
+ double renderStartY = startY + offsetY;
+ double renderStartZ = startZ + offsetZ;
+ double renderEndX = endX + offsetX;
+ double renderEndY = endY + offsetY;
+ double renderEndZ = endZ + offsetZ;
+
+ // Calculate perpendicular vectors for the beam rectangle
+ double dx = renderEndX - renderStartX;
+ double dy = renderEndY - renderStartY;
+ double dz = renderEndZ - renderStartZ;
+ double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
+ if (len < 0.001) {
+ restoreRenderState();
+ return;
+ }
+
+ // Normalize direction
+ dx /= len;
+ dy /= len;
+ dz /= len;
+
+ // 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;
+ }
+
+ // Cross product for horizontal perpendicular
+ double horzX = dy * upZ - dz * upY;
+ double horzY = dz * upX - dx * upZ;
+ double horzZ = dx * upY - dy * upX;
+ double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ);
+ if (horzLen > 0) {
+ horzX /= horzLen;
+ horzY /= horzLen;
+ horzZ /= horzLen;
+ }
+
+ // Cross product for vertical perpendicular
+ double vertX = dy * horzZ - dz * horzY;
+ 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;
+
+ // Render outer rectangle (larger, outer color, translucent) - only if enabled
+ // outerColorWidth is an additive offset from inner width
+ if (laser.isOuterColorEnabled()) {
+ 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 * 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 * 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 * 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);
+ }
+
+ restoreRenderState();
+ }
+
+ private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) {
+ float headSize = laser.getLaserWidth() * 0.5f;
+ float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks);
+ float size = headSize * chargeProgress;
+
+ if (size <= 0.01f) return;
+
+ int innerColor = laser.getInnerColor();
+ int outerColor = laser.getOuterColor();
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Pulsing effect
+ float pulseTime = laser.ticksExisted + partialTicks;
+ float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f;
+ float scale = size * (1.0f + scaleModifier);
+
+ // Render lightning during charging if enabled
+ if (laser.hasLightningEffect()) {
+ renderAttachedLightning(laser, 0.6f * 0.5f, scale);
+ }
+
+ GL11.glPushMatrix();
+ GL11.glScalef(scale, scale, scale);
+
+ // Inner scale defines the core size
+ float innerScale = 0.6f;
+
+ // Render outer glow only if enabled
+ if (laser.isOuterColorEnabled()) {
+ float outerScale = innerScale + laser.getOuterColorWidth();
+ float outerAlpha = laser.getOuterColorAlpha() * proximityAlpha;
+ GL11.glDepthMask(false);
+ GL11.glPushMatrix();
+ GL11.glScalef(outerScale, outerScale, outerScale);
+ renderCube(outerColor, outerAlpha, 0.5f);
+ GL11.glPopMatrix();
+ GL11.glDepthMask(true);
+ }
+
+ // Render inner core
+ GL11.glScalef(innerScale, innerScale, innerScale);
+ renderCube(innerColor, laser.getInnerAlpha() * proximityAlpha, 0.5f);
+
+ GL11.glPopMatrix();
+ GL11.glPopMatrix();
+ }
+
+ /**
+ * 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) {
+ AttachedLightningRenderer.LightningState state = getLightningState(laser);
+
+ float density = laser.getLightningDensity();
+ // Lightning radius extends outward from inner width
+ float innerRadius = width * 0.6f * 0.5f;
+ float radius = innerRadius + laser.getLightningRadius() * width;
+ int outerColor = laser.getOuterColor();
+ int innerColor = laser.getInnerColor();
+ int fadeTime = laser.getLightningFadeTime();
+
+ // Render lightning at multiple points along the laser
+ // Start, middle, and end points
+ double midX = (startX + endX) * 0.5;
+ double midY = (startY + endY) * 0.5;
+ double midZ = (startZ + endZ) * 0.5;
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(midX, midY, midZ);
+ state.update(density, radius, outerColor, innerColor, fadeTime);
+ state.render();
+ GL11.glPopMatrix();
+
+ // Also render at the tip
+ GL11.glPushMatrix();
+ GL11.glTranslated(endX, endY, endZ);
+ // Use a secondary state for the tip
+ AttachedLightningRenderer.LightningState tipState = getTipLightningState(laser);
+ tipState.update(density * 0.7f, radius * 0.8f, outerColor, innerColor, fadeTime);
+ tipState.render();
+ GL11.glPopMatrix();
+ }
+
+
+ /**
+ * Get or create the tip lightning state for the laser.
+ * Persisted per entity ID so arcs accumulate and fade properly across frames.
+ */
+ private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) {
+ 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) {
+ float[] rgb = extractRGB(color);
+ float r = rgb[0], g = rgb[1], b = rgb[2];
+
+ float halfWidth = width * 0.5f;
+
+ // Calculate 8 corners of the box
+ // Start corners
+ double s1x = x1 - horzX * halfWidth - vertX * halfWidth;
+ double s1y = y1 - horzY * halfWidth - vertY * halfWidth;
+ double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth;
+
+ double s2x = x1 + horzX * halfWidth - vertX * halfWidth;
+ double s2y = y1 + horzY * halfWidth - vertY * halfWidth;
+ double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth;
+
+ double s3x = x1 + horzX * halfWidth + vertX * halfWidth;
+ double s3y = y1 + horzY * halfWidth + vertY * halfWidth;
+ double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth;
+
+ double s4x = x1 - horzX * halfWidth + vertX * halfWidth;
+ double s4y = y1 - horzY * halfWidth + vertY * halfWidth;
+ double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth;
+
+ // End corners
+ double e1x = x2 - horzX * halfWidth - vertX * halfWidth;
+ double e1y = y2 - horzY * halfWidth - vertY * halfWidth;
+ double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth;
+
+ double e2x = x2 + horzX * halfWidth - vertX * halfWidth;
+ double e2y = y2 + horzY * halfWidth - vertY * halfWidth;
+ double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth;
+
+ double e3x = x2 + horzX * halfWidth + vertX * halfWidth;
+ double e3y = y2 + horzY * halfWidth + vertY * halfWidth;
+ double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth;
+
+ double e4x = x2 - horzX * halfWidth + vertX * halfWidth;
+ double e4y = y2 - horzY * halfWidth + vertY * halfWidth;
+ double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth;
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, alpha);
+
+ // Bottom face
+ tess.addVertex(s1x, s1y, s1z);
+ tess.addVertex(s2x, s2y, s2z);
+ tess.addVertex(e2x, e2y, e2z);
+ tess.addVertex(e1x, e1y, e1z);
+
+ // Top face
+ tess.addVertex(s4x, s4y, s4z);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(s3x, s3y, s3z);
+
+ // Left face
+ tess.addVertex(s1x, s1y, s1z);
+ tess.addVertex(e1x, e1y, e1z);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.addVertex(s4x, s4y, s4z);
+
+ // Right face
+ tess.addVertex(s2x, s2y, s2z);
+ tess.addVertex(s3x, s3y, s3z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(e2x, e2y, e2z);
+
+ // Start cap
+ tess.addVertex(s1x, s1y, s1z);
+ tess.addVertex(s4x, s4y, s4z);
+ tess.addVertex(s3x, s3y, s3z);
+ tess.addVertex(s2x, s2y, s2z);
+
+ // End cap
+ tess.addVertex(e1x, e1y, e1z);
+ tess.addVertex(e2x, e2y, e2z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(e4x, e4y, e4z);
+
+ tess.draw();
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java
new file mode 100644
index 000000000..5efe83222
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderEnergyOrb.java
@@ -0,0 +1,97 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+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;
+
+/**
+ * Renders the AbilityOrb entity as a cube with inner and outer layers.
+ * Minecraft-style blocky appearance using Tessellator.
+ */
+@SideOnly(Side.CLIENT)
+public class RenderEnergyOrb extends RenderEnergy {
+
+ private static final int LIGHTNING_FADE_TICKS = 6;
+
+ @Override
+ 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();
+ GL11.glTranslated(x, y, z);
+
+ // Get interpolated size for smooth rendering
+ float size = orb.getInterpolatedSize(partialTicks);
+
+ // Pulsing scale effect
+ float pulseTime = entity.ticksExisted + partialTicks;
+ float scaleModifier = (float) Math.sin(pulseTime * 0.15f) * 0.05f;
+ float scale = size * (1.0f + scaleModifier);
+
+ // Render lightning BEFORE rotation so it crackles in all directions
+ if (orb.hasLightningEffect()) {
+ 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
+ GL11.glRotatef(orb.getInterpolatedRotationX(partialTicks), 1.0f, 0.0f, 0.0f);
+ GL11.glRotatef(orb.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
+ GL11.glRotatef(orb.getInterpolatedRotationZ(partialTicks), 0.0f, 0.0f, 1.0f);
+
+ GL11.glPushMatrix();
+ GL11.glScalef(scale, scale, scale);
+
+ // 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()) {
+ float outerScale = innerScale + orb.getOuterColorWidth();
+ GL11.glDepthMask(false);
+ GL11.glPushMatrix();
+ GL11.glScalef(outerScale, outerScale, outerScale);
+ 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(), orb.getInnerAlpha() * proximityAlpha, 0.5f);
+
+ GL11.glPopMatrix();
+ GL11.glPopMatrix();
+
+ restoreRenderState();
+ }
+
+}
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/RenderSweeper.java b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java
new file mode 100644
index 000000000..01ec9b429
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/RenderSweeper.java
@@ -0,0 +1,235 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.relauncher.Side;
+import cpw.mods.fml.relauncher.SideOnly;
+import kamkeel.npcs.entity.EntityEnergySweeper;
+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;
+
+/**
+ * Renders the Sweeper beam as a thin rotating laser attached to the NPC.
+ * Uses similar rendering style to the Beam trail for visual consistency.
+ */
+@SideOnly(Side.CLIENT)
+public class RenderSweeper extends Render {
+
+ @Override
+ public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
+ 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();
+ float outerColorWidth = sweeper.getOuterColorWidth();
+ float angle = sweeper.getInterpolatedAngle(partialTicks);
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(x, y, z);
+
+ // Rotate the beam around Y axis (angle already includes baseYaw)
+ 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, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth);
+
+ GL11.glPopMatrix();
+
+ restoreRenderState();
+ }
+
+ 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);
+
+ // Force full brightness - prevents world lighting from darkening sweeper
+ 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();
+ }
+
+ /**
+ * 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, float height, int innerColor, int outerColor,
+ boolean outerColorEnabled, float outerColorWidth) {
+ // Extract colors
+ 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;
+
+ // 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) - 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, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f);
+ GL11.glDepthMask(true);
+
+ // 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)
+ renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f);
+ }
+
+ /**
+ * 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 height, float r, float g, float b, float a) {
+ // 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;
+
+ // Normalize direction
+ dx /= len;
+ dy /= len;
+ dz /= len;
+
+ // Calculate perpendicular vectors
+ double upX = 0, upY = 1, upZ = 0;
+ if (Math.abs(dy) > 0.9) {
+ upX = 1;
+ upY = 0;
+ upZ = 0;
+ }
+
+ // Cross product for horizontal perpendicular
+ double horzX = dy * upZ - dz * upY;
+ double horzY = dz * upX - dx * upZ;
+ double horzZ = dx * upY - dy * upX;
+ double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ);
+ if (horzLen > 0) {
+ horzX /= horzLen;
+ horzY /= horzLen;
+ horzZ /= horzLen;
+ }
+
+ // Cross product for vertical perpendicular
+ double vertX = dy * horzZ - dz * horzY;
+ double vertY = dz * horzX - dx * horzZ;
+ double vertZ = dx * horzY - dy * horzX;
+
+ float halfWidth = width * 0.5f;
+ float halfHeight = height * 0.5f;
+
+ // 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 * halfHeight;
+ double s2y = y1 + horzY * halfWidth - vertY * halfHeight;
+ double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight;
+
+ 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 * halfHeight;
+ double s4y = y1 - horzY * halfWidth + vertY * halfHeight;
+ double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight;
+
+ 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 * halfHeight;
+ double e2y = y2 + horzY * halfWidth - vertY * halfHeight;
+ double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight;
+
+ 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 * halfHeight;
+ double e4y = y2 - horzY * halfWidth + vertY * halfHeight;
+ double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight;
+
+ Tessellator tess = Tessellator.instance;
+ tess.startDrawingQuads();
+ tess.setColorRGBA_F(r, g, b, a);
+
+ // Bottom face
+ tess.addVertex(s1x, s1y, s1z);
+ tess.addVertex(s2x, s2y, s2z);
+ tess.addVertex(e2x, e2y, e2z);
+ tess.addVertex(e1x, e1y, e1z);
+
+ // Top face
+ tess.addVertex(s4x, s4y, s4z);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(s3x, s3y, s3z);
+
+ // Left face
+ tess.addVertex(s1x, s1y, s1z);
+ tess.addVertex(e1x, e1y, e1z);
+ tess.addVertex(e4x, e4y, e4z);
+ tess.addVertex(s4x, s4y, s4z);
+
+ // Right face
+ tess.addVertex(s2x, s2y, s2z);
+ tess.addVertex(s3x, s3y, s3z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(e2x, e2y, e2z);
+
+ // End cap (tip of beam)
+ tess.addVertex(e1x, e1y, e1z);
+ tess.addVertex(e2x, e2y, e2z);
+ tess.addVertex(e3x, e3y, e3z);
+ tess.addVertex(e4x, e4y, e4z);
+
+ tess.draw();
+ }
+
+ @Override
+ protected ResourceLocation getEntityTexture(Entity entity) {
+ return null;
+ }
+}
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
new file mode 100644
index 000000000..dc653e73f
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/TelegraphRenderer.java
@@ -0,0 +1,425 @@
+package kamkeel.npcs.client.renderer;
+
+import cpw.mods.fml.common.eventhandler.SubscribeEvent;
+import kamkeel.npcs.controllers.data.telegraph.Telegraph;
+import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
+import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
+import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
+import net.minecraft.client.Minecraft;
+import net.minecraft.client.renderer.Tessellator;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraftforge.client.event.RenderWorldLastEvent;
+import org.lwjgl.opengl.GL11;
+
+/**
+ * Renders telegraph warning shapes in the world.
+ * Register this as an event handler on the Forge event bus.
+ */
+public class TelegraphRenderer {
+
+ public static TelegraphRenderer Instance;
+
+ private static final int CIRCLE_SEGMENTS = 32;
+ private static final int CONE_SEGMENTS = 16;
+
+ public TelegraphRenderer() {
+ Instance = this;
+ }
+
+ @SubscribeEvent
+ public void onRenderWorldLast(RenderWorldLastEvent event) {
+ if (TelegraphManager.ClientInstance == null || !TelegraphManager.ClientInstance.hasTelegraphs()) {
+ return;
+ }
+
+ Minecraft mc = Minecraft.getMinecraft();
+ EntityPlayer player = mc.thePlayer;
+ if (player == null) return;
+
+ float partialTicks = event.partialTicks;
+
+ // Get player interpolated position for camera offset
+ double playerX = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks;
+ double playerY = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks;
+ double playerZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks;
+
+ // Setup GL state for transparent rendering
+ GL11.glPushMatrix();
+ 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.glDepthMask(false);
+
+ // Render each telegraph
+ for (TelegraphInstance instance : TelegraphManager.ClientInstance.getTelegraphs()) {
+ renderTelegraph(instance, playerX, playerY, playerZ, partialTicks);
+ }
+
+ // Restore GL state
+ GL11.glDepthMask(true);
+ GL11.glEnable(GL11.GL_LIGHTING);
+ GL11.glDisable(GL11.GL_BLEND);
+ GL11.glEnable(GL11.GL_CULL_FACE);
+ GL11.glEnable(GL11.GL_TEXTURE_2D);
+
+ GL11.glPopAttrib();
+ GL11.glPopMatrix();
+ }
+
+ private void renderTelegraph(TelegraphInstance instance, double playerX, double playerY, double playerZ, float partialTicks) {
+ Telegraph telegraph = instance.getTelegraph();
+ if (telegraph == null || telegraph.getType() == TelegraphType.NONE) {
+ return;
+ }
+
+ // Calculate render position relative to camera using interpolated positions for smooth movement
+ double renderX = instance.getInterpolatedX(partialTicks) - playerX;
+ double renderY = instance.getInterpolatedY(partialTicks) - playerY + telegraph.getHeightOffset();
+ double renderZ = instance.getInterpolatedZ(partialTicks) - playerZ;
+
+ // Get animated color
+ int color = instance.getAnimatedColor(partialTicks);
+ float alpha = ((color >> 24) & 0xFF) / 255.0f;
+ float red = ((color >> 16) & 0xFF) / 255.0f;
+ float green = ((color >> 8) & 0xFF) / 255.0f;
+ float blue = (color & 0xFF) / 255.0f;
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(renderX, renderY, renderZ);
+
+ // Rotate for directional shapes using interpolated yaw for smooth rotation
+ GL11.glRotatef(-instance.getInterpolatedYaw(partialTicks), 0, 1, 0);
+
+ switch (telegraph.getType()) {
+ case CIRCLE:
+ renderCircle(telegraph.getRadius(), red, green, blue, alpha);
+ break;
+ case RING:
+ renderRing(telegraph.getRadius(), telegraph.getInnerRadius(), red, green, blue, alpha);
+ break;
+ case LINE:
+ renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
+ break;
+ case CONE:
+ 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;
+ }
+
+ GL11.glPopMatrix();
+ }
+
+ private void renderCircle(float radius, float r, float g, float b, float a) {
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ // Center point
+ tessellator.addVertex(0, 0, 0);
+
+ // Circle points
+ for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
+ double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
+ double x = Math.cos(angle) * radius;
+ double z = Math.sin(angle) * radius;
+ tessellator.addVertex(x, 0, z);
+ }
+
+ tessellator.draw();
+
+ // Draw border
+ renderCircleBorder(radius, r, g, b, Math.min(1.0f, a * 2));
+ }
+
+ private void renderCircleBorder(float radius, float r, float g, float b, float a) {
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawing(GL11.GL_LINE_LOOP);
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ for (int i = 0; i < CIRCLE_SEGMENTS; i++) {
+ double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
+ double x = Math.cos(angle) * radius;
+ double z = Math.sin(angle) * radius;
+ tessellator.addVertex(x, 0.01, z);
+ }
+
+ tessellator.draw();
+ }
+
+ private void renderRing(float outerRadius, float innerRadius, float r, float g, float b, float a) {
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawing(GL11.GL_TRIANGLE_STRIP);
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
+ double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
+ double cosA = Math.cos(angle);
+ double sinA = Math.sin(angle);
+
+ // Outer point
+ tessellator.addVertex(cosA * outerRadius, 0, sinA * outerRadius);
+ // Inner point
+ tessellator.addVertex(cosA * innerRadius, 0, sinA * innerRadius);
+ }
+
+ tessellator.draw();
+
+ // Draw borders
+ renderCircleBorder(outerRadius, r, g, b, Math.min(1.0f, a * 2));
+ renderCircleBorder(innerRadius, r, g, b, Math.min(1.0f, a * 2));
+ }
+
+ private void renderLine(float length, float width, float r, float g, float b, float a) {
+ float halfWidth = width / 2;
+
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawingQuads();
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ // Rectangle from origin forward
+ tessellator.addVertex(-halfWidth, 0, 0);
+ tessellator.addVertex(halfWidth, 0, 0);
+ tessellator.addVertex(halfWidth, 0, length);
+ tessellator.addVertex(-halfWidth, 0, length);
+
+ tessellator.draw();
+
+ // Draw border
+ tessellator.startDrawing(GL11.GL_LINE_LOOP);
+ tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
+
+ tessellator.addVertex(-halfWidth, 0.01, 0);
+ tessellator.addVertex(halfWidth, 0.01, 0);
+ tessellator.addVertex(halfWidth, 0.01, length);
+ tessellator.addVertex(-halfWidth, 0.01, length);
+
+ tessellator.draw();
+ }
+
+ 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;
+
+ if (innerRadius <= 0) {
+ // Standard cone: triangle fan from origin
+ tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ 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();
+ }
+ }
+
+ private void renderPoint(float r, float g, float b, float a) {
+ float size = 0.5f;
+
+ Tessellator tessellator = Tessellator.instance;
+ tessellator.startDrawingQuads();
+ tessellator.setColorRGBA_F(r, g, b, a);
+
+ // Diamond shape
+ tessellator.addVertex(0, 0, -size);
+ tessellator.addVertex(size, 0, 0);
+ tessellator.addVertex(0, 0, size);
+ tessellator.addVertex(-size, 0, 0);
+
+ 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 ====================
+
+ /**
+ * Render a telegraph in GUI space for ability preview.
+ * This is used by the Manage Abilities GUI to show telegraph shapes.
+ *
+ * @param instance The telegraph instance to render
+ * @param centerX X center position in GUI space
+ * @param centerY Y center position in GUI space
+ * @param centerZ Z center position in GUI space
+ * @param scale Scale factor for the telegraph
+ * @param partialTicks Partial ticks for interpolation
+ */
+ public void renderTelegraphInGUI(TelegraphInstance instance,
+ double centerX, double centerY, double centerZ,
+ float scale, float partialTicks) {
+ if (instance == null) return;
+
+ Telegraph telegraph = instance.getTelegraph();
+ if (telegraph == null || telegraph.getType() == TelegraphType.NONE) {
+ return;
+ }
+
+ // Get animated color
+ int color = instance.getAnimatedColor(partialTicks);
+ float alpha = ((color >> 24) & 0xFF) / 255.0f;
+ float red = ((color >> 16) & 0xFF) / 255.0f;
+ float green = ((color >> 8) & 0xFF) / 255.0f;
+ float blue = (color & 0xFF) / 255.0f;
+
+ // Setup GL state
+ GL11.glPushMatrix();
+ 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.glDepthMask(false);
+
+ GL11.glTranslated(centerX, centerY, centerZ);
+ GL11.glScalef(scale, scale, scale);
+
+ // Rotate for directional shapes
+ GL11.glRotatef(-instance.getInterpolatedYaw(partialTicks), 0, 1, 0);
+
+ // Render based on type
+ switch (telegraph.getType()) {
+ case CIRCLE:
+ renderCircle(telegraph.getRadius(), red, green, blue, alpha);
+ break;
+ case RING:
+ renderRing(telegraph.getRadius(), telegraph.getInnerRadius(), red, green, blue, alpha);
+ break;
+ case LINE:
+ renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
+ break;
+ case CONE:
+ 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;
+ }
+
+ // Restore GL state
+ GL11.glDepthMask(true);
+ GL11.glEnable(GL11.GL_LIGHTING);
+ GL11.glDisable(GL11.GL_BLEND);
+ GL11.glEnable(GL11.GL_CULL_FACE);
+ GL11.glEnable(GL11.GL_TEXTURE_2D);
+
+ GL11.glPopAttrib();
+ GL11.glPopMatrix();
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java
new file mode 100644
index 000000000..4debb90d6
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/AttachedLightningRenderer.java
@@ -0,0 +1,304 @@
+package kamkeel.npcs.client.renderer.lightning;
+
+import net.minecraft.client.renderer.Tessellator;
+import org.lwjgl.opengl.GL11;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Random;
+
+/**
+ * Renders lightning arcs attached to an entity (in local space).
+ * Supports both instant arcs and fading persistent bolts that move with the entity.
+ */
+public class AttachedLightningRenderer {
+
+ private static final Random rand = new Random();
+
+ /**
+ * Data for a single lightning bolt with fading support.
+ */
+ public static class LightningArc {
+ public List points;
+ public int age;
+ public int maxAge;
+ public int outerColor;
+ public int innerColor;
+
+ public LightningArc(List points, int maxAge, int outerColor, int innerColor) {
+ this.points = points;
+ this.age = 0;
+ this.maxAge = maxAge;
+ this.outerColor = outerColor;
+ this.innerColor = innerColor;
+ }
+
+ public float getAlphaMultiplier() {
+ // Fade out over lifetime
+ if (maxAge <= 0) return 0.0f;
+ return 1.0f - ((float) age / (float) maxAge);
+ }
+
+ public boolean isDead() {
+ return age >= maxAge;
+ }
+
+ public void tick() {
+ age++;
+ }
+ }
+
+ /**
+ * Storage for persistent lightning arcs per entity.
+ * Call updateAndRender() each frame from the entity's renderer.
+ */
+ public static class LightningState {
+ private final List arcs = new ArrayList<>();
+ private float spawnAccumulator = 0;
+
+ /**
+ * Update arc ages, remove dead arcs, spawn new ones based on density.
+ *
+ * @param density Arcs per tick (can be fractional)
+ * @param radius Max arc distance from center
+ * @param outerColor Outer glow color
+ * @param innerColor Inner core color
+ * @param maxAge How many ticks arcs live (for fading)
+ */
+ public void update(float density, float radius, int outerColor, int innerColor, int maxAge) {
+ // Age existing arcs and remove dead ones
+ Iterator iter = arcs.iterator();
+ while (iter.hasNext()) {
+ LightningArc arc = iter.next();
+ arc.tick();
+ if (arc.isDead()) {
+ iter.remove();
+ }
+ }
+
+ // Spawn new arcs based on density
+ spawnAccumulator += density;
+ while (spawnAccumulator >= 1.0f) {
+ spawnAccumulator -= 1.0f;
+ arcs.add(createArc(radius, outerColor, innerColor, maxAge));
+ }
+ }
+
+ /**
+ * 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.
+ * Note: Expects the caller to have already set up GL state (disabled textures,
+ * disabled lighting, disabled culling, enabled blending). This avoids nesting
+ * glPushAttrib calls which can overflow the GL attrib stack (depth 16) when
+ * other mods also push attribs during entity rendering.
+ */
+ public void render() {
+ if (arcs.isEmpty()) return;
+
+ GL11.glDepthMask(false);
+
+ Tessellator tess = Tessellator.instance;
+
+ for (LightningArc arc : arcs) {
+ float alphaMult = arc.getAlphaMultiplier();
+
+ // Render outer glow
+ renderBoltPath(tess, arc.points, arc.outerColor, 0.025f, 0.35f * alphaMult);
+
+ // Render inner core
+ renderBoltPath(tess, arc.points, arc.innerColor, 0.012f, 0.7f * alphaMult);
+ }
+
+ GL11.glDepthMask(true);
+ }
+
+ public int getArcCount() {
+ return arcs.size();
+ }
+ }
+
+ /**
+ * Create a new lightning arc from center to a random point.
+ */
+ private static LightningArc createArc(float radius, int outerColor, int innerColor, int maxAge) {
+ // Random end point on sphere
+ double theta = rand.nextDouble() * Math.PI * 2;
+ double phi = Math.acos(2 * rand.nextDouble() - 1);
+ double r = radius * (0.5 + rand.nextDouble() * 0.5);
+
+ double endX = r * Math.sin(phi) * Math.cos(theta);
+ double endY = r * Math.sin(phi) * Math.sin(theta);
+ double endZ = r * Math.cos(phi);
+
+ int segments = 4 + rand.nextInt(3);
+ float displacement = radius * 0.25f;
+
+ List points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement);
+
+ return new LightningArc(points, maxAge, outerColor, innerColor);
+ }
+
+ /**
+ * 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) {
+ List points = new ArrayList<>();
+ points.add(new double[]{x1, y1, z1});
+
+ double dx = x2 - x1;
+ double dy = y2 - y1;
+ double dz = z2 - z1;
+
+ // Create perpendicular vectors for displacement
+ Vec3d dir = new Vec3d(dx, dy, dz);
+ Vec3d perp1 = dir.copy().perpendicular().normalize();
+ Vec3d perp2 = dir.copy().crossProduct(perp1).normalize();
+
+ for (int i = 1; i < segments; i++) {
+ double t = (double) i / segments;
+
+ double px = x1 + dx * t;
+ double py = y1 + dy * t;
+ double pz = z1 + dz * t;
+
+ // Displacement strongest in middle
+ float strength = (float) (1.0 - Math.abs(t - 0.5) * 2.0) * displacement;
+ double offset1 = (rand.nextDouble() - 0.5) * 2 * strength;
+ double offset2 = (rand.nextDouble() - 0.5) * 2 * strength;
+
+ px += perp1.x * offset1 + perp2.x * offset2;
+ py += perp1.y * offset1 + perp2.y * offset2;
+ pz += perp1.z * offset1 + perp2.z * offset2;
+
+ points.add(new double[]{px, py, pz});
+ }
+
+ points.add(new double[]{x2, y2, z2});
+ return points;
+ }
+
+ /**
+ * Render the lightning path as quads.
+ */
+ private static void renderBoltPath(Tessellator tess, List points, int color, float width, float alpha) {
+ if (alpha <= 0.01f) return;
+
+ 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++) {
+ double[] p1 = points.get(i);
+ double[] p2 = points.get(i + 1);
+
+ double segDx = p2[0] - p1[0];
+ double segDy = p2[1] - p1[1];
+ double segDz = p2[2] - p1[2];
+
+ Vec3d segDir = new Vec3d(segDx, segDy, segDz);
+ Vec3d perp = segDir.copy().perpendicular().normalize().multiply(width);
+
+ // First quad
+ tess.startDrawingQuads();
+ tess.setBrightness(0xF000F0);
+ tess.setColorRGBA(r, g, b, a);
+
+ tess.addVertex(p1[0] - perp.x, p1[1] - perp.y, p1[2] - perp.z);
+ tess.addVertex(p1[0] + perp.x, p1[1] + perp.y, p1[2] + perp.z);
+ tess.addVertex(p2[0] + perp.x, p2[1] + perp.y, p2[2] + perp.z);
+ tess.addVertex(p2[0] - perp.x, p2[1] - perp.y, p2[2] - perp.z);
+
+ tess.draw();
+
+ // Second quad (perpendicular for 3D look)
+ Vec3d perp2 = segDir.copy().crossProduct(perp).normalize().multiply(width);
+
+ tess.startDrawingQuads();
+ tess.setBrightness(0xF000F0);
+ tess.setColorRGBA(r, g, b, a);
+
+ tess.addVertex(p1[0] - perp2.x, p1[1] - perp2.y, p1[2] - perp2.z);
+ tess.addVertex(p1[0] + perp2.x, p1[1] + perp2.y, p1[2] + perp2.z);
+ tess.addVertex(p2[0] + perp2.x, p2[1] + perp2.y, p2[2] + perp2.z);
+ tess.addVertex(p2[0] - perp2.x, p2[1] - perp2.y, p2[2] - perp2.z);
+
+ tess.draw();
+ }
+ }
+
+ /**
+ * 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) ====================
+
+ /**
+ * Render a single instant lightning arc (no fading, drawn this frame only).
+ * Expects the caller to have already set up GL state (disabled textures,
+ * disabled lighting, disabled culling, enabled blending).
+ */
+ public static void renderInstantArc(float radius, int outerColor, int innerColor) {
+ double theta = rand.nextDouble() * Math.PI * 2;
+ double phi = Math.acos(2 * rand.nextDouble() - 1);
+ double r = radius * (0.5 + rand.nextDouble() * 0.5);
+
+ double endX = r * Math.sin(phi) * Math.cos(theta);
+ double endY = r * Math.sin(phi) * Math.sin(theta);
+ double endZ = r * Math.cos(phi);
+
+ int segments = 4 + rand.nextInt(3);
+ float displacement = radius * 0.25f;
+
+ List points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement);
+
+ GL11.glDepthMask(false);
+
+ Tessellator tess = Tessellator.instance;
+ renderBoltPath(tess, points, outerColor, 0.025f, 0.35f);
+ renderBoltPath(tess, points, innerColor, 0.012f, 0.7f);
+
+ GL11.glDepthMask(true);
+ }
+
+ /**
+ * Render multiple instant arcs.
+ */
+ public static void renderCracklingLightning(int count, float radius, int outerColor, int innerColor) {
+ for (int i = 0; i < count; i++) {
+ renderInstantArc(radius, outerColor, innerColor);
+ }
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java
new file mode 100644
index 000000000..beea63fd3
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningBolt.java
@@ -0,0 +1,295 @@
+package kamkeel.npcs.client.renderer.lightning;
+
+import net.minecraft.world.World;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Random;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+/**
+ * Lightning bolt data model with fractal segment generation.
+ * Adapted from Botania's LightningBolt by Vazkii/ChickenBones.
+ */
+public class LightningBolt {
+
+ public static ConcurrentLinkedQueue boltList = new ConcurrentLinkedQueue<>();
+
+ public ArrayList segments = new ArrayList<>();
+ public Vec3d start;
+ public Vec3d end;
+
+ public double length;
+ public int numSegments0;
+ private int numSplits;
+ private boolean finalized;
+ private Random rand;
+ public long seed;
+
+ public int particleAge;
+ public int particleMaxAge;
+ public boolean isDead;
+
+ private World world;
+ private HashMap splitParents = new HashMap<>();
+
+ public float speed = 1.5F;
+ public static final int FADE_TIME = 4; // Short lifespan for projectile-attached lightning
+
+ public int colorOuter;
+ public int colorInner;
+
+ public LightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, long seed, int colorOuter, int colorInner) {
+ this.world = world;
+ this.seed = seed;
+ this.rand = new Random(seed);
+
+ this.start = start;
+ this.end = end;
+ this.speed = ticksPerMeter;
+
+ this.colorOuter = colorOuter;
+ this.colorInner = colorInner;
+
+ this.numSegments0 = 1;
+ this.length = end.copy().subtract(start).mag();
+ 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));
+ }
+
+ /**
+ * Apply default fractal splitting for natural-looking lightning.
+ */
+ public void defaultFractal() {
+ fractal(2, length / 1.5, 0.7F, 0.7F, 45);
+ fractal(2, length / 4, 0.5F, 0.8F, 50);
+ fractal(2, length / 15, 0.5F, 0.9F, 55);
+ fractal(2, length / 30, 0.5F, 1.0F, 60);
+ fractal(2, length / 60, 0, 0, 0);
+ fractal(2, length / 100, 0, 0, 0);
+ fractal(2, length / 400, 0, 0, 0);
+ }
+
+ /**
+ * Simplified fractal for short-lived projectile lightning.
+ * Less detail but faster and more appropriate for fast-moving objects.
+ */
+ public void simpleFractal() {
+ fractal(2, length / 2.0, 0.4F, 0.6F, 35);
+ fractal(2, length / 6, 0.3F, 0.7F, 40);
+ fractal(2, length / 20, 0, 0, 0);
+ }
+
+ /**
+ * Apply fractal splitting to create branching lightning.
+ *
+ * @param splits Number of splits per segment
+ * @param amount Displacement amount
+ * @param splitChance Probability of branching (0-1)
+ * @param splitLength Length multiplier for branches
+ * @param splitAngle Angle for branch splits in degrees
+ */
+ public void fractal(int splits, double amount, double splitChance, double splitLength, double splitAngle) {
+ if (finalized) return;
+
+ ArrayList oldSegments = segments;
+ segments = new ArrayList<>();
+
+ Segment prev = null;
+
+ for (Segment segment : oldSegments) {
+ prev = segment.prev;
+
+ Vec3d subSegment = segment.diff.copy().multiply(1.0 / splits);
+
+ BoltPoint[] newPoints = new BoltPoint[splits + 1];
+
+ Vec3d startPoint = segment.startPoint.point;
+ newPoints[0] = segment.startPoint;
+ newPoints[splits] = segment.endPoint;
+
+ for (int i = 1; i < splits; i++) {
+ Vec3d randOff = segment.diff.copy().perpendicular().normalize()
+ .rotate(rand.nextFloat() * 360, segment.diff);
+ randOff.multiply((rand.nextFloat() - 0.5F) * amount * 2);
+
+ Vec3d basePoint = startPoint.copy().add(subSegment.copy().multiply(i));
+
+ newPoints[i] = new BoltPoint(basePoint, randOff);
+ }
+
+ for (int i = 0; i < splits; i++) {
+ Segment next = new Segment(newPoints[i], newPoints[i + 1], segment.light,
+ segment.segmentNo * splits + i, segment.splitNo);
+ next.prev = prev;
+ if (prev != null) {
+ prev.next = next;
+ }
+
+ if (i != 0 && rand.nextFloat() < splitChance) {
+ Vec3d splitRot = next.diff.copy().xCrossProduct()
+ .rotate(rand.nextFloat() * 360, next.diff);
+ Vec3d diff = next.diff.copy()
+ .rotate((rand.nextFloat() * 0.66F + 0.33F) * splitAngle, splitRot)
+ .multiply(splitLength);
+
+ numSplits++;
+ splitParents.put(numSplits, next.splitNo);
+
+ Segment split = new Segment(newPoints[i],
+ new BoltPoint(newPoints[i + 1].basePoint, newPoints[i + 1].offsetVec.copy().add(diff)),
+ segment.light / 2F, next.segmentNo, numSplits);
+ split.prev = prev;
+
+ segments.add(split);
+ }
+
+ prev = next;
+ segments.add(next);
+ }
+
+ if (segment.next != null) {
+ segment.next.prev = prev;
+ }
+ }
+
+ numSegments0 *= splits;
+ }
+
+ /**
+ * Finalize the bolt after all fractal passes.
+ */
+ public void finalizeBolt() {
+ if (finalized) return;
+ finalized = true;
+
+ calculateEndDiffs();
+ Collections.sort(segments, new SegmentLightSorter());
+ }
+
+ private void calculateEndDiffs() {
+ Collections.sort(segments, new SegmentSorter());
+
+ for (Segment segment : segments) {
+ segment.calcEndDiffs();
+ }
+ }
+
+ public void onUpdate() {
+ particleAge++;
+ if (particleAge >= particleMaxAge) {
+ isDead = true;
+ }
+ }
+
+ /**
+ * Update all active lightning bolts. Called from client tick handler.
+ */
+ public static void updateAll() {
+ for (Iterator iterator = boltList.iterator(); iterator.hasNext(); ) {
+ LightningBolt bolt = iterator.next();
+ bolt.onUpdate();
+ if (bolt.isDead) {
+ iterator.remove();
+ }
+ }
+ }
+
+ // ==================== INNER CLASSES ====================
+
+ public class BoltPoint {
+ public Vec3d point;
+ public Vec3d basePoint;
+ public Vec3d offsetVec;
+
+ public BoltPoint(Vec3d basePoint, Vec3d offsetVec) {
+ this.point = basePoint.copy().add(offsetVec);
+ this.basePoint = basePoint;
+ this.offsetVec = offsetVec;
+ }
+ }
+
+ public class Segment {
+ public BoltPoint startPoint;
+ public BoltPoint endPoint;
+
+ public Vec3d diff;
+ public Segment prev;
+ public Segment next;
+
+ public Vec3d nextDiff;
+ public Vec3d prevDiff;
+
+ public float sinPrev;
+ public float sinNext;
+ public float light;
+
+ public int segmentNo;
+ public int splitNo;
+
+ public Segment(BoltPoint start, BoltPoint end, float light, int segmentNo, int splitNo) {
+ this.startPoint = start;
+ this.endPoint = end;
+ this.light = light;
+ this.segmentNo = segmentNo;
+ this.splitNo = splitNo;
+ calcDiff();
+ }
+
+ 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);
+ }
+
+ public void calcDiff() {
+ diff = endPoint.point.copy().subtract(startPoint.point);
+ }
+
+ public void calcEndDiffs() {
+ if (prev != null) {
+ Vec3d prevDiffNorm = prev.diff.copy().normalize();
+ Vec3d thisDiffNorm = diff.copy().normalize();
+
+ prevDiff = thisDiffNorm.copy().add(prevDiffNorm).normalize();
+ sinPrev = (float) Math.sin(thisDiffNorm.angle(prevDiffNorm.multiply(-1)) / 2);
+ } else {
+ prevDiff = diff.copy().normalize();
+ sinPrev = 1;
+ }
+
+ if (next != null) {
+ Vec3d nextDiffNorm = next.diff.copy().normalize();
+ Vec3d thisDiffNorm = diff.copy().normalize();
+
+ nextDiff = thisDiffNorm.add(nextDiffNorm).normalize();
+ sinNext = (float) Math.sin(thisDiffNorm.angle(nextDiffNorm.multiply(-1)) / 2);
+ } else {
+ nextDiff = diff.copy().normalize();
+ sinNext = 1;
+ }
+ }
+ }
+
+ public class SegmentSorter implements Comparator {
+ @Override
+ public int compare(Segment o1, Segment o2) {
+ int comp = Integer.compare(o1.splitNo, o2.splitNo);
+ if (comp == 0) {
+ return Integer.compare(o1.segmentNo, o2.segmentNo);
+ }
+ return comp;
+ }
+ }
+
+ public class SegmentLightSorter implements Comparator {
+ @Override
+ public int compare(Segment o1, Segment o2) {
+ return Float.compare(o2.light, o1.light);
+ }
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java
new file mode 100644
index 000000000..d3f9aeedd
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/LightningHandler.java
@@ -0,0 +1,201 @@
+package kamkeel.npcs.client.renderer.lightning;
+
+import cpw.mods.fml.common.eventhandler.SubscribeEvent;
+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.Tessellator;
+import net.minecraft.client.renderer.texture.TextureManager;
+import net.minecraft.entity.Entity;
+import net.minecraft.util.ResourceLocation;
+import net.minecraft.world.World;
+import net.minecraftforge.client.event.RenderWorldLastEvent;
+import org.lwjgl.opengl.GL11;
+
+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)
+public class LightningHandler {
+
+ private static final ResourceLocation TEXTURE_OUTER = new ResourceLocation("customnpcs", "textures/effects/lightning_outer.png");
+ private static final ResourceLocation TEXTURE_INNER = new ResourceLocation("customnpcs", "textures/effects/lightning_inner.png");
+
+ public static int lightningCount = 0;
+
+ private static Vec3d getRelativeViewVector(Vec3d pos) {
+ Entity renderEntity = Minecraft.getMinecraft().renderViewEntity;
+ return new Vec3d(
+ (float) renderEntity.posX - pos.x,
+ (float) renderEntity.posY + renderEntity.getEyeHeight() - pos.y,
+ (float) renderEntity.posZ - pos.z
+ );
+ }
+
+ @SubscribeEvent
+ public void onRenderWorldLast(RenderWorldLastEvent event) {
+ float partialTicks = event.partialTicks;
+ Entity entity = Minecraft.getMinecraft().thePlayer;
+ TextureManager textureManager = Minecraft.getMinecraft().renderEngine;
+
+ double interpPosX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks;
+ double interpPosY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks;
+ double interpPosZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks;
+
+ if (LightningBolt.boltList.isEmpty()) {
+ return;
+ }
+
+ GL11.glPushMatrix();
+ GL11.glTranslated(-interpPosX, -interpPosY, -interpPosZ);
+
+ Tessellator tessellator = Tessellator.instance;
+
+ GL11.glDepthMask(false);
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
+ GL11.glDisable(GL11.GL_TEXTURE_2D);
+ GL11.glDisable(GL11.GL_LIGHTING);
+ GL11.glDisable(GL11.GL_CULL_FACE);
+
+ lightningCount = 0;
+
+ // Render outer layer (translucent glow)
+ for (LightningBolt bolt : LightningBolt.boltList) {
+ renderBolt(bolt, tessellator, partialTicks, false);
+ }
+
+ // Render inner layer (bright core)
+ for (LightningBolt bolt : LightningBolt.boltList) {
+ renderBolt(bolt, tessellator, partialTicks, true);
+ }
+
+ GL11.glEnable(GL11.GL_CULL_FACE);
+ GL11.glEnable(GL11.GL_LIGHTING);
+ GL11.glEnable(GL11.GL_TEXTURE_2D);
+ GL11.glDisable(GL11.GL_BLEND);
+ GL11.glDepthMask(true);
+
+ GL11.glPopMatrix();
+ }
+
+ private void renderBolt(LightningBolt bolt, Tessellator tessellator, float partialTicks, boolean inner) {
+ lightningCount++;
+
+ float boltAge = bolt.particleAge < 0 ? 0 : (float) bolt.particleAge / (float) bolt.particleMaxAge;
+ float mainAlpha;
+ if (!inner) {
+ mainAlpha = (1 - boltAge) * 0.4F;
+ } else {
+ mainAlpha = 1 - boltAge * 0.5F;
+ }
+
+ int expandTime = (int) (bolt.length * bolt.speed);
+
+ int renderStart = (int) ((expandTime / 2 - bolt.particleMaxAge + bolt.particleAge) / (float) (expandTime / 2) * bolt.numSegments0);
+ int renderEnd = (int) ((bolt.particleAge + expandTime) / (float) expandTime * bolt.numSegments0);
+
+ for (Segment segment : bolt.segments) {
+ if (segment.segmentNo < renderStart || segment.segmentNo > renderEnd) {
+ continue;
+ }
+
+ Vec3d playerVec = getRelativeViewVector(segment.startPoint.point).multiply(-1);
+
+ double width = 0.008F * (playerVec.mag() / 8 + 1) * (1 + segment.light) * 0.4F;
+
+ Vec3d diff1 = playerVec.copy().crossProduct(segment.prevDiff).normalize().multiply(width / segment.sinPrev);
+ Vec3d diff2 = playerVec.copy().crossProduct(segment.nextDiff).normalize().multiply(width / segment.sinNext);
+
+ Vec3d startVec = segment.startPoint.point;
+ Vec3d endVec = segment.endPoint.point;
+
+ int color = inner ? bolt.colorInner : bolt.colorOuter;
+ Color c = new Color(color);
+ int alpha = (int) (mainAlpha * segment.light * c.getAlpha());
+
+ tessellator.startDrawingQuads();
+ tessellator.setBrightness(0xF000F0);
+ tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha);
+
+ tessellator.addVertex(endVec.x - diff2.x, endVec.y - diff2.y, endVec.z - diff2.z);
+ tessellator.addVertex(startVec.x - diff1.x, startVec.y - diff1.y, startVec.z - diff1.z);
+ tessellator.addVertex(startVec.x + diff1.x, startVec.y + diff1.y, startVec.z + diff1.z);
+ tessellator.addVertex(endVec.x + diff2.x, endVec.y + diff2.y, endVec.z + diff2.z);
+
+ tessellator.draw();
+
+ // Rounded end caps
+ if (segment.next == null) {
+ Vec3d roundEnd = segment.endPoint.point.copy().add(segment.diff.copy().normalize().multiply(width));
+
+ tessellator.startDrawingQuads();
+ tessellator.setBrightness(0xF000F0);
+ tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha);
+
+ tessellator.addVertex(roundEnd.x - diff2.x, roundEnd.y - diff2.y, roundEnd.z - diff2.z);
+ tessellator.addVertex(endVec.x - diff2.x, endVec.y - diff2.y, endVec.z - diff2.z);
+ tessellator.addVertex(endVec.x + diff2.x, endVec.y + diff2.y, endVec.z + diff2.z);
+ tessellator.addVertex(roundEnd.x + diff2.x, roundEnd.y + diff2.y, roundEnd.z + diff2.z);
+
+ tessellator.draw();
+ }
+
+ if (segment.prev == null) {
+ Vec3d roundEnd = segment.startPoint.point.copy().subtract(segment.diff.copy().normalize().multiply(width));
+
+ tessellator.startDrawingQuads();
+ tessellator.setBrightness(0xF000F0);
+ tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha);
+
+ tessellator.addVertex(startVec.x - diff1.x, startVec.y - diff1.y, startVec.z - diff1.z);
+ tessellator.addVertex(roundEnd.x - diff1.x, roundEnd.y - diff1.y, roundEnd.z - diff1.z);
+ tessellator.addVertex(roundEnd.x + diff1.x, roundEnd.y + diff1.y, roundEnd.z + diff1.z);
+ tessellator.addVertex(startVec.x + diff1.x, startVec.y + diff1.y, startVec.z + diff1.z);
+
+ tessellator.draw();
+ }
+ }
+ }
+
+ /**
+ * Spawn a lightning bolt between two points.
+ *
+ * @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)
+ */
+ 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);
+ bolt.defaultFractal();
+ bolt.finalizeBolt();
+ LightningBolt.boltList.add(bolt);
+ }
+
+ /**
+ * Spawn a lightning bolt with automatic seed.
+ */
+ public static void spawnLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, int colorOuter, int colorInner) {
+ spawnLightningBolt(world, start, end, ticksPerMeter, System.nanoTime(), colorOuter, colorInner);
+ }
+
+ /**
+ * Spawn a simple lightning bolt for projectiles - less detail, faster.
+ */
+ public static void spawnSimpleLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, int colorOuter, int colorInner) {
+ LightningBolt bolt = new LightningBolt(world, start, end, ticksPerMeter, System.nanoTime(), colorOuter, colorInner);
+ bolt.simpleFractal();
+ bolt.finalizeBolt();
+ LightningBolt.boltList.add(bolt);
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/Quaternion.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/Quaternion.java
new file mode 100644
index 000000000..cda0307b7
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/Quaternion.java
@@ -0,0 +1,85 @@
+package kamkeel.npcs.client.renderer.lightning;
+
+/**
+ * Quaternion class for axis-angle rotations in lightning calculations.
+ * Adapted from Botania's Quat by ChickenBones.
+ */
+public class Quaternion {
+ public double x;
+ public double y;
+ public double z;
+ public double s;
+
+ public Quaternion() {
+ s = 1.0;
+ x = 0.0;
+ y = 0.0;
+ z = 0.0;
+ }
+
+ public Quaternion(Quaternion quat) {
+ x = quat.x;
+ y = quat.y;
+ z = quat.z;
+ s = quat.s;
+ }
+
+ public Quaternion(double s, double x, double y, double z) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ this.s = s;
+ }
+
+ public static Quaternion aroundAxis(double ax, double ay, double az, double angle) {
+ angle *= 0.5;
+ double sinAngle = Math.sin(angle);
+ return new Quaternion(Math.cos(angle), ax * sinAngle, ay * sinAngle, az * sinAngle);
+ }
+
+ public static Quaternion aroundAxis(Vec3d axis, double angle) {
+ return aroundAxis(axis.x, axis.y, axis.z, angle);
+ }
+
+ public void multiply(Quaternion quat) {
+ double d = s * quat.s - x * quat.x - y * quat.y - z * quat.z;
+ double d1 = s * quat.x + x * quat.s - y * quat.z + z * quat.y;
+ double d2 = s * quat.y + x * quat.z + y * quat.s - z * quat.x;
+ double d3 = s * quat.z - x * quat.y + y * quat.x + z * quat.s;
+ s = d;
+ x = d1;
+ y = d2;
+ z = d3;
+ }
+
+ public double mag() {
+ return Math.sqrt(x * x + y * y + z * z + s * s);
+ }
+
+ public void normalize() {
+ double d = mag();
+ if (d == 0.0) {
+ return;
+ }
+ d = 1.0 / d;
+ x *= d;
+ y *= d;
+ z *= d;
+ s *= d;
+ }
+
+ public void rotate(Vec3d vec) {
+ double d = -x * vec.x - y * vec.y - z * vec.z;
+ double d1 = s * vec.x + y * vec.z - z * vec.y;
+ double d2 = s * vec.y - x * vec.z + z * vec.x;
+ double d3 = s * vec.z + x * vec.y - y * vec.x;
+ vec.x = d1 * s - d * x - d2 * z + d3 * y;
+ vec.y = d2 * s - d * y + d1 * z - d3 * x;
+ vec.z = d3 * s - d * z - d1 * y + d2 * x;
+ }
+
+ @Override
+ public String toString() {
+ return "Quaternion(" + s + ", " + x + ", " + y + ", " + z + ")";
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/client/renderer/lightning/Vec3d.java b/src/main/java/kamkeel/npcs/client/renderer/lightning/Vec3d.java
new file mode 100644
index 000000000..018e55bdb
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/client/renderer/lightning/Vec3d.java
@@ -0,0 +1,184 @@
+package kamkeel.npcs.client.renderer.lightning;
+
+import net.minecraft.entity.Entity;
+import net.minecraft.util.Vec3;
+import org.lwjgl.opengl.GL11;
+
+/**
+ * 3D Vector helper class for lightning calculations.
+ * Adapted from Botania's Vector3 by ChickenBones.
+ */
+public class Vec3d {
+ public double x;
+ public double y;
+ public double z;
+
+ public Vec3d() {
+ }
+
+ public Vec3d(double x, double y, double z) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+
+ public Vec3d(Vec3d vec) {
+ this.x = vec.x;
+ this.y = vec.y;
+ this.z = vec.z;
+ }
+
+ public Vec3d(Vec3 vec) {
+ this.x = vec.xCoord;
+ this.y = vec.yCoord;
+ this.z = vec.zCoord;
+ }
+
+ public Vec3d copy() {
+ return new Vec3d(this);
+ }
+
+ public static Vec3d fromEntity(Entity e) {
+ return new Vec3d(e.posX, e.posY, e.posZ);
+ }
+
+ public static Vec3d fromEntityCenter(Entity e) {
+ return new Vec3d(e.posX, e.posY - e.yOffset + e.height / 2, e.posZ);
+ }
+
+ public Vec3d set(double x, double y, double z) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ return this;
+ }
+
+ public Vec3d set(Vec3d vec) {
+ this.x = vec.x;
+ this.y = vec.y;
+ this.z = vec.z;
+ return this;
+ }
+
+ public double dotProduct(Vec3d vec) {
+ double d = vec.x * x + vec.y * y + vec.z * z;
+ if (d > 1 && d < 1.00001) d = 1;
+ else if (d < -1 && d > -1.00001) d = -1;
+ return d;
+ }
+
+ public Vec3d crossProduct(Vec3d vec) {
+ double d = y * vec.z - z * vec.y;
+ double d1 = z * vec.x - x * vec.z;
+ double d2 = x * vec.y - y * vec.x;
+ x = d;
+ y = d1;
+ z = d2;
+ return this;
+ }
+
+ public Vec3d add(double x, double y, double z) {
+ this.x += x;
+ this.y += y;
+ this.z += z;
+ return this;
+ }
+
+ public Vec3d add(Vec3d vec) {
+ this.x += vec.x;
+ this.y += vec.y;
+ this.z += vec.z;
+ return this;
+ }
+
+ public Vec3d subtract(Vec3d vec) {
+ this.x -= vec.x;
+ this.y -= vec.y;
+ this.z -= vec.z;
+ return this;
+ }
+
+ public Vec3d multiply(double d) {
+ this.x *= d;
+ this.y *= d;
+ this.z *= d;
+ return this;
+ }
+
+ public double mag() {
+ return Math.sqrt(x * x + y * y + z * z);
+ }
+
+ public double magSquared() {
+ return x * x + y * y + z * z;
+ }
+
+ public Vec3d normalize() {
+ double d = mag();
+ if (d != 0) {
+ multiply(1 / d);
+ }
+ return this;
+ }
+
+ public Vec3d perpendicular() {
+ if (z == 0) {
+ return zCrossProduct();
+ }
+ return xCrossProduct();
+ }
+
+ public Vec3d xCrossProduct() {
+ double d = z;
+ double d1 = -y;
+ x = 0;
+ y = d;
+ z = d1;
+ return this;
+ }
+
+ public Vec3d zCrossProduct() {
+ double d = y;
+ double d1 = -x;
+ x = d;
+ y = d1;
+ z = 0;
+ return this;
+ }
+
+ public Vec3 toVec3() {
+ return Vec3.createVectorHelper(x, y, z);
+ }
+
+ public double angle(Vec3d vec) {
+ return Math.acos(copy().normalize().dotProduct(vec.copy().normalize()));
+ }
+
+ public Vec3d negate() {
+ x = -x;
+ y = -y;
+ z = -z;
+ return this;
+ }
+
+ public Vec3d rotate(double angle, Vec3d axis) {
+ Quaternion.aroundAxis(axis.copy().normalize(), angle).rotate(this);
+ return this;
+ }
+
+ public void glVertex() {
+ GL11.glVertex3d(x, y, z);
+ }
+
+ @Override
+ public String toString() {
+ return "Vec3d(" + x + ", " + y + ", " + z + ")";
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof Vec3d)) return false;
+ Vec3d v = (Vec3d) o;
+ return x == v.x && y == v.y && z == v.z;
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/command/AbilityCommand.java b/src/main/java/kamkeel/npcs/command/AbilityCommand.java
new file mode 100644
index 000000000..982a975b3
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/command/AbilityCommand.java
@@ -0,0 +1,434 @@
+package kamkeel.npcs.command;
+
+import kamkeel.npcs.controllers.AbilityController;
+import kamkeel.npcs.controllers.data.ability.Ability;
+import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
+import kamkeel.npcs.controllers.data.ability.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;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import static kamkeel.npcs.util.ColorUtil.sendError;
+import static kamkeel.npcs.util.ColorUtil.sendResult;
+
+public class AbilityCommand extends CommandKamkeelBase {
+
+ @Override
+ public String getCommandName() {
+ return "ability";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Ability operations";
+ }
+
+ @SubCommand(
+ desc = "List all custom abilities"
+ )
+ public void list(ICommandSender sender, String[] args) {
+ Set names = AbilityController.Instance.getCustomAbilityNames();
+ if (names.isEmpty()) {
+ sendResult(sender, "No custom abilities found.");
+ return;
+ }
+
+ sendResult(sender, "Custom Abilities (" + names.size() + "):");
+ for (String name : names) {
+ Ability ability = AbilityController.Instance.getCustomAbility(name);
+ if (ability != null) {
+ sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ")");
+ } else {
+ sendResult(sender, " - \u00A7b" + name);
+ }
+ }
+ }
+
+ @SubCommand(
+ desc = "List all registered ability types"
+ )
+ public void types(ICommandSender sender, String[] args) {
+ String[] typeIds = AbilityController.Instance.getTypes();
+ if (typeIds.length == 0) {
+ sendResult(sender, "No ability types registered.");
+ return;
+ }
+
+ List sortedTypes = new ArrayList<>();
+ for (String typeId : typeIds) {
+ sortedTypes.add(typeId);
+ }
+ Collections.sort(sortedTypes);
+
+ sendResult(sender, "Registered Ability Types (" + sortedTypes.size() + "):");
+ for (String typeId : sortedTypes) {
+ sendResult(sender, " - \u00A7d" + typeId);
+ }
+ }
+
+ @SubCommand(
+ desc = "Reload abilities from disk"
+ )
+ public void reload(ICommandSender sender, String[] args) {
+ AbilityController.Instance.load();
+ sendResult(sender, "Abilities and chained abilities reloaded from disk.");
+ }
+
+ @SubCommand(
+ 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 ");
+ return;
+ }
+
+ String name = joinArgs(args, 0);
+ if (!AbilityController.Instance.hasCustomAbilityName(name)) {
+ sendError(sender, "No custom ability with name: " + name);
+ return;
+ }
+
+ AbilityController.Instance.deleteCustomAbility(name);
+ sendResult(sender, "Deleted ability: \u00A7b" + name);
+ }
+
+ @SubCommand(
+ desc = "Get info about an ability",
+ usage = ""
+ )
+ public void info(ICommandSender sender, String[] args) {
+ if (args.length < 1) {
+ sendError(sender, "Usage: /kam ability info ");
+ return;
+ }
+
+ 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.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");
+ if (ability.isInterruptible()) {
+ sendResult(sender, " Dazed: \u00A7e" + ability.getDazedTicks() + " ticks");
+ }
+ sendResult(sender, " Range: \u00A7e" + ability.getMinRange() + " - " + ability.getMaxRange());
+ sendResult(sender, " Telegraph: \u00A7e" + (ability.isShowTelegraph() ? "Yes" : "No"));
+ sendResult(sender, " Allowed By: \u00A7e" + ability.getAllowedBy().name());
+ }
+
+ @SubCommand(
+ desc = "List all built-in abilities available for players"
+ )
+ public void prebuilts(ICommandSender sender, String[] args) {
+ Set names = AbilityController.Instance.getAbilityNames();
+ if (names.isEmpty()) {
+ sendResult(sender, "No built-in abilities found.");
+ return;
+ }
+
+ List playerAbilities = new ArrayList<>();
+ for (String name : names) {
+ Ability ability = AbilityController.Instance.getAbility(name);
+ if (ability != null && ability.getAllowedBy().allowsPlayer()) {
+ playerAbilities.add(name);
+ }
+ }
+
+ if (playerAbilities.isEmpty()) {
+ sendResult(sender, "No player-usable built-in abilities found.");
+ return;
+ }
+
+ Collections.sort(playerAbilities);
+ sendResult(sender, "Built-in Player Abilities (" + playerAbilities.size() + "):");
+ for (String name : playerAbilities) {
+ Ability ability = AbilityController.Instance.getAbility(name);
+ String userType = ability.getAllowedBy() == UserType.PLAYER_ONLY ? "\u00A7d[PLAYER]" : "\u00A7a[BOTH]";
+ sendResult(sender, " - \u00A7b" + name + " " + userType);
+ }
+ }
+
+ @SubCommand(
+ desc = "Give an ability to a player",
+ usage = " "
+ )
+ public void give(ICommandSender sender, String[] args) {
+ if (args.length < 2) {
+ sendError(sender, "Usage: /kam ability give ");
+ return;
+ }
+
+ String playerName = args[0];
+ String abilityKey = joinArgs(args, 1);
+
+ EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
+ if (player == null) {
+ sendError(sender, "Player not found: " + playerName);
+ return;
+ }
+
+ Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
+ if (ability == null) {
+ sendError(sender, "Ability not found: " + abilityKey);
+ return;
+ }
+
+ // Use the ability's canonical ID for storage (registry key for built-in, UUID for custom)
+ String canonicalKey = ability.getId();
+ if (canonicalKey == null || canonicalKey.isEmpty()) {
+ canonicalKey = abilityKey;
+ }
+ String displayName = ability.getDisplayName();
+
+ if (!ability.getAllowedBy().allowsPlayer()) {
+ sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players.");
+ return;
+ }
+
+ PlayerData data = PlayerDataController.Instance.getPlayerData(player);
+ if (data.abilityData.hasUnlockedAbility(canonicalKey)) {
+ sendError(sender, "Player already has ability: " + displayName);
+ return;
+ }
+
+ data.abilityData.unlockAbility(canonicalKey);
+ sendResult(sender, "Gave ability '\u00A7b" + displayName + "\u00A77' to player \u00A7a" + playerName);
+ }
+
+ @SubCommand(
+ desc = "Remove an ability from a player",
+ usage = " "
+ )
+ public void remove(ICommandSender sender, String[] args) {
+ if (args.length < 2) {
+ sendError(sender, "Usage: /kam ability remove ");
+ return;
+ }
+
+ String playerName = args[0];
+ String abilityKey = joinArgs(args, 1);
+
+ EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
+ if (player == null) {
+ sendError(sender, "Player not found: " + playerName);
+ return;
+ }
+
+ Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
+ if (ability == null) {
+ sendError(sender, "Ability not found: " + abilityKey);
+ return;
+ }
+ String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
+ String displayName = ability.getDisplayName();
+
+ PlayerData data = PlayerDataController.Instance.getPlayerData(player);
+ if (!data.abilityData.hasUnlockedAbility(canonicalKey)) {
+ sendError(sender, "Player doesn't have ability: " + displayName);
+ return;
+ }
+
+ data.abilityData.lockAbility(canonicalKey);
+ sendResult(sender, "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(
+ desc = "List abilities unlocked for a player",
+ usage = ""
+ )
+ public void player(ICommandSender sender, String[] args) {
+ if (args.length < 1) {
+ sendError(sender, "Usage: /kam ability player ");
+ return;
+ }
+
+ String playerName = args[0];
+
+ // Find player
+ EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
+ if (player == null) {
+ sendError(sender, "Player not found: " + playerName);
+ return;
+ }
+
+ PlayerData data = PlayerDataController.Instance.getPlayerData(player);
+ String[] abilityKeys = data.abilityData.getUnlockedAbilities();
+
+ if (abilityKeys.length == 0) {
+ sendResult(sender, "Player \u00A7a" + playerName + "\u00A77 has no unlocked abilities.");
+ return;
+ }
+
+ sendResult(sender, "Abilities for \u00A7a" + playerName + "\u00A77 (" + abilityKeys.length + "):");
+ int selected = data.abilityData.getSelectedIndex();
+ for (int i = 0; i < abilityKeys.length; i++) {
+ String key = abilityKeys[i];
+ String prefix = (i == selected) ? "\u00A7e> " : " ";
+
+ 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 {
+ // 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);
+ }
+ }
+ }
+ }
+
+ private String joinArgs(String[] args, int startIndex) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = startIndex; i < args.length; i++) {
+ if (i > startIndex) sb.append(" ");
+ sb.append(args[i]);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Get list of player-usable ability 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() {
+ 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
new file mode 100644
index 000000000..a56dce671
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/command/AuctionCommand.java
@@ -0,0 +1,185 @@
+package kamkeel.npcs.command;
+
+import kamkeel.npcs.command.auction.BlacklistSubCommand;
+import net.minecraft.command.CommandException;
+import net.minecraft.command.ICommandSender;
+import net.minecraft.entity.player.EntityPlayer;
+import noppes.npcs.NoppesUtilServer;
+import noppes.npcs.config.ConfigMarket;
+import noppes.npcs.constants.EnumGuiType;
+import noppes.npcs.controllers.AuctionController;
+import noppes.npcs.controllers.PlayerDataController;
+import noppes.npcs.controllers.data.AuctionListing;
+import noppes.npcs.controllers.data.PlayerData;
+
+import java.util.List;
+import java.util.UUID;
+
+import static kamkeel.npcs.util.ColorUtil.sendError;
+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();
+ registerNestedCommand(new BlacklistSubCommand());
+ }
+
+ @Override
+ public String getCommandName() {
+ return "auction";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Auction operations";
+ }
+
+ @SubCommand(
+ desc = "List active auctions",
+ usage = "[page]"
+ )
+ public void list(ICommandSender sender, String[] args) throws CommandException {
+ if (!ConfigMarket.AuctionEnabled) {
+ sendError(sender, "Auction system is disabled");
+ return;
+ }
+
+ AuctionController controller = AuctionController.getInstance();
+ if (controller == null) {
+ sendError(sender, "Auction system is not available");
+ return;
+ }
+
+ int page = 1;
+ if (args.length > 0) {
+ try {
+ page = Integer.parseInt(args[0]);
+ } catch (NumberFormatException ex) {
+ sendError(sender, "Invalid page number: " + args[0]);
+ return;
+ }
+ }
+
+ 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 / COMMAND_PAGE_SIZE));
+
+ if (listings.isEmpty()) {
+ sendMessage(sender, "\u00A77No active auctions found");
+ return;
+ }
+
+ sendMessage(sender, String.format("\u00A76=== Active Auctions (Page %d/%d) ===", page, totalPages));
+ for (AuctionListing listing : listings) {
+ String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown";
+ String price = listing.hasBids() ?
+ String.format("%,d (bid)", listing.currentBid) :
+ String.format("%,d (start)", listing.startingPrice);
+ sendMessage(sender, String.format("\u00A7e%s \u00A77by \u00A7b%s\u00A77 - \u00A76%s %s",
+ itemName, listing.sellerName, price, ConfigMarket.CurrencyName));
+ }
+ }
+
+ @SubCommand(
+ desc = "View player's auction activity",
+ usage = ""
+ )
+ public void view(ICommandSender sender, String[] args) throws CommandException {
+ if (!ConfigMarket.AuctionEnabled) {
+ sendError(sender, "Auction system is disabled");
+ return;
+ }
+
+ AuctionController controller = AuctionController.getInstance();
+ if (controller == null) {
+ sendError(sender, "Auction system is not available");
+ return;
+ }
+
+ if (args.length < 1) {
+ throw new CommandException("Usage: /auction view ");
+ }
+
+ String playername = args[0];
+ List dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
+
+ if (dataList.isEmpty()) {
+ sendError(sender, "Unknown player: " + playername);
+ return;
+ }
+
+ for (PlayerData playerdata : dataList) {
+ UUID playerUUID = UUID.fromString(playerdata.uuid);
+ List activeListings = controller.getPlayerActiveListings(playerUUID);
+ List activeBids = controller.getPlayerActiveBids(playerUUID);
+ int claimCount = controller.getPlayerClaims(playerUUID).size();
+
+ sendMessage(sender, String.format("\u00A76=== Auction Activity for %s ===", playerdata.playername));
+ sendMessage(sender, String.format("\u00A77Active Listings: \u00A7e%d", activeListings.size()));
+ sendMessage(sender, String.format("\u00A77Active Bids: \u00A7e%d", activeBids.size()));
+ sendMessage(sender, String.format("\u00A77Pending Claims: \u00A7e%d", claimCount));
+
+ if (!activeListings.isEmpty()) {
+ sendMessage(sender, "\u00A7a--- Selling ---");
+ for (AuctionListing listing : activeListings) {
+ String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown";
+ String price = listing.hasBids() ?
+ String.format("%,d (bid)", listing.currentBid) :
+ String.format("%,d (start)", listing.startingPrice);
+ sendMessage(sender, String.format(" \u00A7e%s \u00A77- \u00A76%s", itemName, price));
+ }
+ }
+
+ if (!activeBids.isEmpty()) {
+ sendMessage(sender, "\u00A7e--- Bidding ---");
+ for (AuctionListing bid : activeBids) {
+ String itemName = bid.item != null ? bid.item.getDisplayName() : "Unknown";
+ sendMessage(sender, String.format(" \u00A7e%s \u00A77- \u00A76%,d %s",
+ itemName, bid.currentBid, ConfigMarket.CurrencyName));
+ }
+ }
+ }
+ }
+
+ @SubCommand(
+ desc = "Open the Auction GUI",
+ usage = "",
+ permission = 0
+ )
+ public void open(ICommandSender sender, String[] args) throws CommandException {
+ if (!ConfigMarket.AuctionEnabled) {
+ sendError(sender, "Auction system is disabled");
+ return;
+ }
+
+ if (!(sender instanceof EntityPlayer)) {
+ sendError(sender, "This command can only be used by players");
+ return;
+ }
+
+ EntityPlayer player = (EntityPlayer) sender;
+
+ // Open the auction GUI without requiring an NPC
+ NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, null);
+ sendResult(sender, "Opening Auction...");
+ }
+
+ @Override
+ public List addTabCompletionOptions(ICommandSender sender, String[] args) {
+ if (args.length == 1) {
+ return getListOfStringsMatchingLastWord(args, getAllSubCommandNames());
+ }
+
+ // Delegate to nested commands for deeper tab completion
+ List nestedCompletions = getNestedTabCompletions(sender, args);
+ if (nestedCompletions != null) {
+ return nestedCompletions;
+ }
+
+ return null;
+ }
+}
diff --git a/src/main/java/kamkeel/npcs/command/CloneCommand.java b/src/main/java/kamkeel/npcs/command/CloneCommand.java
index 027ff228e..312293ca5 100644
--- a/src/main/java/kamkeel/npcs/command/CloneCommand.java
+++ b/src/main/java/kamkeel/npcs/command/CloneCommand.java
@@ -13,6 +13,7 @@ import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import noppes.npcs.controllers.ServerCloneController;
+import noppes.npcs.controllers.data.CloneFolder;
import noppes.npcs.entity.EntityNPCInterface;
import java.util.List;
@@ -35,20 +36,24 @@ public class CloneCommand extends CommandKamkeelBase {
@SubCommand(
desc = "Add NPC(s) to clone storage",
- usage = " [clonedname]",
+ usage = " [clonedname]",
permission = 4
)
public void add(ICommandSender sender, String[] args) {
- int tab = 0;
+ int tab = -1;
+ String folder = null;
try {
tab = Integer.parseInt(args[1]);
- if (tab < 0 || tab > 15) {
+ if (tab < 1 || tab > 15) {
sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
- sendError(sender, String.format("Tab is not a number: %s", args[1]));
- return;
+ folder = args[1];
+ if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
+ sendError(sender, String.format("Unknown folder: %s", folder));
+ return;
+ }
}
int x = sender.getPlayerCoordinates().posX;
@@ -64,32 +69,47 @@ public class CloneCommand extends CommandKamkeelBase {
NBTTagCompound compound = new NBTTagCompound();
if (!npc.writeToNBTOptional(compound))
return;
- ServerCloneController.Instance.addClone(compound, name, tab);
- sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab));
+ if (folder != null) {
+ ServerCloneController.Instance.addClone(compound, name, folder);
+ sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Folder \u00A7b%s\u00A77", name, folder));
+ } else {
+ ServerCloneController.Instance.addClone(compound, name, tab);
+ sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab));
+ }
}
}
}
@SubCommand(
desc = "List NPC from clone storage",
- usage = "",
+ usage = "",
permission = 2
)
public void list(ICommandSender sender, String[] args) {
sendMessage(sender, "--- Stored NPCs --- (server side)");
- int tab = 0;
+ int tab = -1;
+ String folder = null;
try {
tab = Integer.parseInt(args[1]);
- if (tab < 0 || tab > 15) {
+ if (tab < 1 || tab > 15) {
sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
- sendError(sender, String.format("Tab is not a number: %s", args[1]));
- return;
+ folder = args[1];
+ if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
+ sendError(sender, String.format("Unknown folder: %s", folder));
+ return;
+ }
}
- for (String name : ServerCloneController.Instance.getClones(tab)) {
+ List clones;
+ if (folder != null) {
+ clones = ServerCloneController.Instance.getClones(folder);
+ } else {
+ clones = ServerCloneController.Instance.getClones(tab);
+ }
+ for (String name : clones) {
sendMessage(sender, name);
}
sendMessage(sender, "------------------------------------");
@@ -97,59 +117,75 @@ public class CloneCommand extends CommandKamkeelBase {
@SubCommand(
desc = "Remove NPC from clone storage",
- usage = " ",
+ usage = " ",
permission = 4
)
public void del(ICommandSender sender, String[] args) throws CommandException {
String nametodel = args[0];
- int tab = 0;
+ int tab = -1;
+ String folder = null;
try {
tab = Integer.parseInt(args[1]);
- if (tab < 0 || tab > 15) {
- sendError(sender, String.format("Tab must be within 1-15"));
+ if (tab < 1 || tab > 15) {
+ sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
- sendError(sender, String.format("Tab is not a number: %s", args[1]));
- return;
- }
-
- boolean deleted = false;
- for (String name : ServerCloneController.Instance.getClones(tab)) {
- if (nametodel.equalsIgnoreCase(name)) {
- ServerCloneController.Instance.removeClone(name, tab);
- deleted = true;
- break;
+ folder = args[1];
+ if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
+ sendError(sender, String.format("Unknown folder: %s", folder));
+ return;
}
}
- if (!ServerCloneController.Instance.removeClone(nametodel, tab)) {
+
+ boolean success;
+ if (folder != null) {
+ success = ServerCloneController.Instance.removeClone(nametodel, folder);
+ } else {
+ success = ServerCloneController.Instance.removeClone(nametodel, tab);
+ }
+
+ if (!success) {
sendError(sender, String.format("NPC '%s' was not found", nametodel));
} else {
- sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab));
+ if (folder != null) {
+ sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Folder \u00A7b%s\u00A77", nametodel, folder));
+ } else {
+ sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab));
+ }
}
}
@SubCommand(
desc = "Spawn cloned NPC",
- usage = " [[world:]x,y,z]] [newname]",
+ usage = " [[world:]x,y,z]] [newname]",
permission = 2
)
public void spawn(ICommandSender sender, String[] args) throws CommandException {
String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space
- int tab = 0;
+ int tab = -1;
+ String folder = null;
try {
tab = Integer.parseInt(args[1]);
- if (tab < 0 || tab > 15) {
- sendError(sender, String.format("Tab must be within 1-15"));
+ if (tab < 1 || tab > 15) {
+ sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
- sendError(sender, String.format("Tab is not a number: %s", args[1]));
- return;
+ folder = args[1];
+ if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
+ sendError(sender, String.format("Unknown folder: %s", folder));
+ return;
+ }
}
String newname = null;
- NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
+ NBTTagCompound compound;
+ if (folder != null) {
+ compound = ServerCloneController.Instance.getCloneData(sender, name, folder);
+ } else {
+ compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
+ }
if (compound == null) {
sendError(sender, "Unknown npc");
return;
@@ -211,22 +247,26 @@ public class CloneCommand extends CommandKamkeelBase {
}
@SubCommand(
- desc = "Spawn cloned NPC",
- usage = " [[world:]x,y,z]] [newname]",
+ desc = "Spawn cloned NPC in a grid",
+ usage = " [[world:]x,y,z]] [newname]",
permission = 2
)
public void grid(ICommandSender sender, String[] args) throws CommandException {
String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space
- int tab = 0;
+ int tab = -1;
+ String folder = null;
try {
tab = Integer.parseInt(args[1]);
- if (tab < 0 || tab > 15) {
- sendError(sender, String.format("Tab must be within 1-15"));
+ if (tab < 1 || tab > 15) {
+ sendError(sender, "Tab must be within 1-15");
return;
}
} catch (NumberFormatException ex) {
- sendError(sender, String.format("Tab is not a number: %s", args[1]));
- return;
+ folder = args[1];
+ if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
+ sendError(sender, String.format("Unknown folder: %s", folder));
+ return;
+ }
}
int width, height;
@@ -238,9 +278,13 @@ public class CloneCommand extends CommandKamkeelBase {
return;
}
-
String newname = null;
- NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
+ NBTTagCompound compound;
+ if (folder != null) {
+ compound = ServerCloneController.Instance.getCloneData(sender, name, folder);
+ } else {
+ compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
+ }
if (compound == null) {
sendError(sender, "Unknown npc");
return;
@@ -317,6 +361,163 @@ public class CloneCommand extends CommandKamkeelBase {
return;
}
+ @SubCommand(
+ desc = "List all custom clone folders",
+ usage = "",
+ permission = 2
+ )
+ public void listfolders(ICommandSender sender, String[] args) {
+ if (ServerCloneController.Instance == null) {
+ sendError(sender, "Folder system not initialized");
+ return;
+ }
+ sendMessage(sender, "--- Clone Folders ---");
+ for (CloneFolder f : ServerCloneController.Instance.getFolderList()) {
+ sendMessage(sender, f.name);
+ }
+ sendMessage(sender, "------------------------------------");
+ }
+
+ @SubCommand(
+ desc = "Create a custom clone folder",
+ usage = "",
+ permission = 4
+ )
+ public void createfolder(ICommandSender sender, String[] args) {
+ if (ServerCloneController.Instance == null) {
+ sendError(sender, "Folder system not initialized");
+ return;
+ }
+ String name = args[0];
+ if (!CloneFolder.isValidName(name)) {
+ sendError(sender, String.format("Invalid folder name: %s", name));
+ return;
+ }
+ if (ServerCloneController.Instance.hasFolder(name)) {
+ sendError(sender, String.format("Folder '%s' already exists", name));
+ return;
+ }
+ CloneFolder created = ServerCloneController.Instance.createFolder(name);
+ if (created != null) {
+ sendResult(sender, String.format("Created folder \u00A7b%s", name));
+ } else {
+ sendError(sender, String.format("Failed to create folder '%s'", name));
+ }
+ }
+
+ @SubCommand(
+ desc = "Rename a custom clone folder",
+ usage = " ",
+ permission = 4
+ )
+ public void renamefolder(ICommandSender sender, String[] args) {
+ if (ServerCloneController.Instance == null) {
+ sendError(sender, "Folder system not initialized");
+ return;
+ }
+ String oldName = args[0];
+ String newName = args[1];
+ if (!ServerCloneController.Instance.hasFolder(oldName)) {
+ sendError(sender, String.format("Unknown folder: %s", oldName));
+ return;
+ }
+ if (!CloneFolder.isValidName(newName)) {
+ sendError(sender, String.format("Invalid folder name: %s", newName));
+ return;
+ }
+ if (ServerCloneController.Instance.renameFolder(oldName, newName)) {
+ sendResult(sender, String.format("Renamed folder \u00A7b%s\u00A77 to \u00A7b%s", oldName, newName));
+ } else {
+ sendError(sender, String.format("Failed to rename folder '%s'", oldName));
+ }
+ }
+
+ @SubCommand(
+ desc = "Delete an empty custom clone folder",
+ usage = "",
+ permission = 4
+ )
+ public void deletefolder(ICommandSender sender, String[] args) {
+ if (ServerCloneController.Instance == null) {
+ sendError(sender, "Folder system not initialized");
+ return;
+ }
+ String name = args[0];
+ if (!ServerCloneController.Instance.hasFolder(name)) {
+ sendError(sender, String.format("Unknown folder: %s", name));
+ return;
+ }
+ if (ServerCloneController.Instance.deleteFolder(name)) {
+ sendResult(sender, String.format("Deleted folder \u00A7b%s", name));
+ } else {
+ sendError(sender, String.format("Failed to delete folder '%s' (folder must be empty)", name));
+ }
+ }
+
+ @SubCommand(
+ desc = "Move a clone between tabs/folders",
+ usage = " ",
+ permission = 4
+ )
+ public void move(ICommandSender sender, String[] args) {
+ if (ServerCloneController.Instance == null) {
+ sendError(sender, "Folder system not initialized");
+ return;
+ }
+ String cloneName = args[0];
+
+ int fromTab = -1;
+ String fromFolder = null;
+ try {
+ fromTab = Integer.parseInt(args[1]);
+ if (fromTab < 1 || fromTab > 15) {
+ sendError(sender, "Source tab must be within 1-15");
+ return;
+ }
+ } catch (NumberFormatException ex) {
+ fromFolder = args[1];
+ if (!ServerCloneController.Instance.hasFolder(fromFolder)) {
+ sendError(sender, String.format("Unknown source folder: %s", fromFolder));
+ return;
+ }
+ }
+
+ int toTab = -1;
+ String toFolder = null;
+ try {
+ toTab = Integer.parseInt(args[2]);
+ if (toTab < 1 || toTab > 15) {
+ sendError(sender, "Destination tab must be within 1-15");
+ return;
+ }
+ } catch (NumberFormatException ex) {
+ toFolder = args[2];
+ if (!ServerCloneController.Instance.hasFolder(toFolder)) {
+ sendError(sender, String.format("Unknown destination folder: %s", toFolder));
+ return;
+ }
+ }
+
+ boolean success;
+ if (fromFolder != null && toFolder != null) {
+ success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder);
+ } else if (fromFolder != null) {
+ success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab);
+ } else if (toFolder != null) {
+ success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder);
+ } else {
+ success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab);
+ }
+
+ if (success) {
+ String from = fromFolder != null ? fromFolder : String.valueOf(fromTab);
+ String to = toFolder != null ? toFolder : String.valueOf(toTab);
+ sendResult(sender, String.format("Moved \u00A7e%s\u00A77 from \u00A7b%s\u00A77 to \u00A7b%s", cloneName, from, to));
+ } else {
+ sendError(sender, String.format("Failed to move '%s'", cloneName));
+ }
+ }
+
public World getWorld(String t) {
WorldServer[] ws = MinecraftServer.getServer().worldServers;
for (WorldServer w : ws) {
diff --git a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java
index 76bc80b94..f87068968 100644
--- a/src/main/java/kamkeel/npcs/command/CommandKamkeel.java
+++ b/src/main/java/kamkeel/npcs/command/CommandKamkeel.java
@@ -10,6 +10,7 @@ import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import noppes.npcs.CustomNpcsPermissions;
import noppes.npcs.config.ConfigMain;
+import noppes.npcs.config.ConfigMarket;
import noppes.npcs.scripted.CustomNPCsException;
import java.lang.reflect.Method;
@@ -19,6 +20,8 @@ import java.util.HashMap;
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 {
@@ -43,8 +46,13 @@ public class CommandKamkeel extends CommandBase {
registerCommand(new OverlayCommand());
registerCommand(new CommandCommand());
registerCommand(new EffectCommand());
+ registerCommand(new AbilityCommand());
+ registerCommand(new MoneyCommand());
+ if (ConfigMarket.AuctionEnabled)
+ registerCommand(new AuctionCommand());
if (ConfigMain.AttributesEnabled)
registerCommand(new AttributeCommand());
+ registerCommand(new DebugCommand());
}
public void registerCommand(CommandKamkeelBase command) {
@@ -128,7 +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 = 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()]));
}
}
@@ -136,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 af2366f89..c6ffe7ec1 100644
--- a/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java
+++ b/src/main/java/kamkeel/npcs/command/CommandKamkeelBase.java
@@ -12,12 +12,16 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
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();
+ public Map nestedCommands = new HashMap();
public CommandKamkeelBase() {
for (Method m : this.getClass().getDeclaredMethods()) {
@@ -31,6 +35,14 @@ public abstract class CommandKamkeelBase extends CommandBase {
}
}
+ /**
+ * Register a nested command class as a subcommand.
+ * The nested command's getCommandName() becomes the subcommand name.
+ */
+ public void registerNestedCommand(CommandKamkeelBase command) {
+ nestedCommands.put(command.getCommandName().toLowerCase(), command);
+ }
+
@Override
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
@@ -51,7 +63,7 @@ public abstract class CommandKamkeelBase extends CommandBase {
}
public boolean runSubCommands() {
- return !subcommands.isEmpty();
+ return !subcommands.isEmpty() || !nestedCommands.isEmpty();
}
@Retention(value = RetentionPolicy.RUNTIME)
@@ -71,6 +83,22 @@ public abstract class CommandKamkeelBase extends CommandBase {
}
public void processSubCommand(ICommandSender sender, String command, String[] args) throws CommandException {
+ // Check nested commands first
+ CommandKamkeelBase nested = nestedCommands.get(command.toLowerCase());
+ if (nested != null) {
+ if (!canSendNestedCommand(sender, nested)) {
+ throw new CommandException("You are not allowed to use this command: " + command);
+ }
+
+ if (args.length == 0 || !nested.runSubCommands()) {
+ nested.processCommand(sender, args);
+ } else {
+ nested.processSubCommand(sender, args[0], Arrays.copyOfRange(args, 1, args.length));
+ }
+ return;
+ }
+
+ // Fall back to method subcommands
Method m = subcommands.get(command.toLowerCase());
if (m == null)
throw new CommandException("Unknown subcommand " + command);
@@ -132,4 +160,55 @@ public abstract class CommandKamkeelBase extends CommandBase {
return false;
}
+
+ public boolean canSendNestedCommand(ICommandSender sender, CommandKamkeelBase nested) {
+ int permission = nested.getRequiredPermissionLevel();
+ String subCommand = nested.getCommandName();
+
+ if (sender.canCommandSenderUseCommand(permission, getSubUniversalPermission())) {
+ return true;
+ }
+
+ if (sender.canCommandSenderUseCommand(permission, getSubCommandPermission(subCommand))) {
+ return true;
+ }
+
+ if (sender instanceof EntityPlayer) {
+ return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getSubCommandPermission(subCommand));
+ }
+
+ return false;
+ }
+
+ // =========================================
+ // Tab Completion Helpers
+ // =========================================
+
+ /**
+ * Get all subcommand names (both method-based and nested)
+ */
+ public String[] getAllSubCommandNames() {
+ Set names = new HashSet<>();
+ names.addAll(subcommands.keySet());
+ names.addAll(nestedCommands.keySet());
+ return names.toArray(new String[0]);
+ }
+
+ /**
+ * Get tab completions for nested command at given depth
+ */
+ public List getNestedTabCompletions(ICommandSender sender, String[] args) {
+ if (args.length == 0) return null;
+
+ String subCmd = args[0].toLowerCase();
+ CommandKamkeelBase nested = nestedCommands.get(subCmd);
+
+ if (nested != null && args.length > 1) {
+ // Delegate to nested command
+ String[] nestedArgs = Arrays.copyOfRange(args, 1, args.length);
+ return nested.addTabCompletionOptions(sender, nestedArgs);
+ }
+
+ return null;
+ }
}
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/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/MoneyCommand.java b/src/main/java/kamkeel/npcs/command/MoneyCommand.java
new file mode 100644
index 000000000..ee034243d
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/command/MoneyCommand.java
@@ -0,0 +1,168 @@
+package kamkeel.npcs.command;
+
+import net.minecraft.command.CommandException;
+import net.minecraft.command.ICommandSender;
+import noppes.npcs.config.ConfigMarket;
+import noppes.npcs.controllers.PlayerDataController;
+import noppes.npcs.controllers.data.PlayerData;
+import noppes.npcs.controllers.data.PlayerTradeData;
+
+import java.util.List;
+
+import static kamkeel.npcs.util.ColorUtil.sendError;
+import static kamkeel.npcs.util.ColorUtil.sendResult;
+
+public class MoneyCommand extends CommandKamkeelBase {
+
+ @Override
+ public String getCommandName() {
+ return "money";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Currency operations";
+ }
+
+ @SubCommand(
+ desc = "Show player's balance",
+ usage = ""
+ )
+ public void balance(ICommandSender sender, String[] args) throws CommandException {
+ String playername = args[0];
+ List dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
+
+ if (dataList.isEmpty()) {
+ sendError(sender, "Unknown player: " + playername);
+ return;
+ }
+
+ for (PlayerData playerdata : dataList) {
+ PlayerTradeData currency = playerdata.tradeData;
+ long balance = currency.getBalance();
+ sendResult(sender, String.format("Player \u00A7b%s\u00A77 has \u00A76%,d %s",
+ playerdata.playername, balance, ConfigMarket.CurrencyName));
+ }
+ }
+
+ @SubCommand(
+ desc = "Give currency to player",
+ usage = " "
+ )
+ public void give(ICommandSender sender, String[] args) throws CommandException {
+ String playername = args[0];
+ long amount;
+ try {
+ amount = Long.parseLong(args[1]);
+ } catch (NumberFormatException ex) {
+ sendError(sender, "Invalid amount: " + args[1]);
+ return;
+ }
+
+ if (amount <= 0) {
+ sendError(sender, "Amount must be positive");
+ return;
+ }
+
+ List dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
+
+ if (dataList.isEmpty()) {
+ sendError(sender, "Unknown player: " + playername);
+ return;
+ }
+
+ for (PlayerData playerdata : dataList) {
+ PlayerTradeData currency = playerdata.tradeData;
+ if (currency.deposit(amount)) {
+ playerdata.save();
+ sendResult(sender, String.format("Gave \u00A76%,d %s\u00A77 to player \u00A7b%s\u00A77. New balance: \u00A76%,d",
+ amount, ConfigMarket.CurrencyName, playerdata.playername, currency.getBalance()));
+ } else {
+ sendError(sender, String.format("Failed to give currency to %s (would exceed max balance)",
+ playerdata.playername));
+ }
+ }
+ }
+
+ @SubCommand(
+ desc = "Withdraw currency from player",
+ usage = " "
+ )
+ public void withdraw(ICommandSender sender, String[] args) throws CommandException {
+ String playername = args[0];
+ long amount;
+ try {
+ amount = Long.parseLong(args[1]);
+ } catch (NumberFormatException ex) {
+ sendError(sender, "Invalid amount: " + args[1]);
+ return;
+ }
+
+ if (amount <= 0) {
+ sendError(sender, "Amount must be positive");
+ return;
+ }
+
+ List dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
+
+ if (dataList.isEmpty()) {
+ sendError(sender, "Unknown player: " + playername);
+ return;
+ }
+
+ for (PlayerData playerdata : dataList) {
+ PlayerTradeData currency = playerdata.tradeData;
+ if (currency.withdraw(amount)) {
+ playerdata.save();
+ sendResult(sender, String.format("Withdrew \u00A76%,d %s\u00A77 from player \u00A7b%s\u00A77. New balance: \u00A76%,d",
+ amount, ConfigMarket.CurrencyName, playerdata.playername, currency.getBalance()));
+ } else {
+ sendError(sender, String.format("Failed to withdraw from %s (insufficient funds)",
+ playerdata.playername));
+ }
+ }
+ }
+
+ @SubCommand(
+ desc = "Set player's balance",
+ usage = " "
+ )
+ public void set(ICommandSender sender, String[] args) throws CommandException {
+ String playername = args[0];
+ long amount;
+ try {
+ amount = Long.parseLong(args[1]);
+ } catch (NumberFormatException ex) {
+ sendError(sender, "Invalid amount: " + args[1]);
+ return;
+ }
+
+ if (amount < 0) {
+ sendError(sender, "Amount cannot be negative");
+ return;
+ }
+
+ List dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
+
+ if (dataList.isEmpty()) {
+ sendError(sender, "Unknown player: " + playername);
+ return;
+ }
+
+ for (PlayerData playerdata : dataList) {
+ PlayerTradeData currency = playerdata.tradeData;
+ currency.setBalance(amount);
+ playerdata.save();
+ sendResult(sender, String.format("Set balance of player \u00A7b%s\u00A77 to \u00A76%,d %s",
+ playerdata.playername, currency.getBalance(), ConfigMarket.CurrencyName));
+ }
+ }
+
+ @Override
+ public List addTabCompletionOptions(ICommandSender par1, String[] args) {
+ if (args.length == 1) {
+ return getListOfStringsMatchingLastWord(args, new String[]{"balance", "give", "withdraw", "set"});
+ }
+ return null;
+ }
+}
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..5ccbe5319 100644
--- a/src/main/java/kamkeel/npcs/command/QuestCommand.java
+++ b/src/main/java/kamkeel/npcs/command/QuestCommand.java
@@ -115,7 +115,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();
diff --git a/src/main/java/kamkeel/npcs/command/ScriptCommand.java b/src/main/java/kamkeel/npcs/command/ScriptCommand.java
index 41415cb81..61b380dbd 100644
--- a/src/main/java/kamkeel/npcs/command/ScriptCommand.java
+++ b/src/main/java/kamkeel/npcs/command/ScriptCommand.java
@@ -12,6 +12,7 @@ public class ScriptCommand extends CommandKamkeelBase {
@SubCommand(desc = "Reload scripts data and folders.")
public Boolean reload(ICommandSender sender, String args[]) {
ScriptController.Instance.loadCategories();
+ ScriptController.Instance.syncClientScripts(null);
if (ScriptController.Instance.loadPlayerScripts())
sendResult(sender, "Reload player scripts successfully");
diff --git a/src/main/java/kamkeel/npcs/command/auction/BlacklistSubCommand.java b/src/main/java/kamkeel/npcs/command/auction/BlacklistSubCommand.java
new file mode 100644
index 000000000..a9902a890
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/command/auction/BlacklistSubCommand.java
@@ -0,0 +1,226 @@
+package kamkeel.npcs.command.auction;
+
+import kamkeel.npcs.command.CommandKamkeelBase;
+import net.minecraft.command.CommandException;
+import net.minecraft.command.ICommandSender;
+import net.minecraft.entity.player.EntityPlayer;
+import net.minecraft.item.ItemStack;
+import noppes.npcs.controllers.data.AuctionBlacklist;
+
+import java.util.List;
+
+import static kamkeel.npcs.util.ColorUtil.sendError;
+import static kamkeel.npcs.util.ColorUtil.sendMessage;
+import static kamkeel.npcs.util.ColorUtil.sendResult;
+
+public class BlacklistSubCommand extends CommandKamkeelBase {
+
+ @Override
+ public String getCommandName() {
+ return "blacklist";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Manage auction item blacklist";
+ }
+
+ @Override
+ public void processCommand(ICommandSender sender, String[] args) throws CommandException {
+ // Show help when called with no subcommand
+ sendHelp(sender);
+ }
+
+ private void sendHelp(ICommandSender sender) {
+ sendMessage(sender, "\u00A76=== Auction Blacklist Commands ===");
+ sendMessage(sender, "\u00A7e/cnpc auction blacklist add - ");
+ sendMessage(sender, "\u00A7e/cnpc auction blacklist remove
- ");
+ sendMessage(sender, "\u00A7e/cnpc auction blacklist list [item|mod|nbt]");
+ sendMessage(sender, "\u00A7e/cnpc auction blacklist reload");
+ sendMessage(sender, "\u00A7e/cnpc auction blacklist check \u00A77(checks held item)");
+ }
+
+ @SubCommand(
+ desc = "Add item, mod, or NBT tag to blacklist",
+ usage = "
- "
+ )
+ public void add(ICommandSender sender, String[] args) throws CommandException {
+ if (args.length < 2) {
+ sendError(sender, "Usage: /cnpc auction blacklist add
- ");
+ return;
+ }
+
+ String type = args[0].toLowerCase();
+ String value = args[1];
+
+ switch (type) {
+ case "item":
+ if (AuctionBlacklist.addItem(value)) {
+ sendResult(sender, "Added item to blacklist: " + value);
+ } else {
+ sendError(sender, "Failed to add item to blacklist");
+ }
+ break;
+ case "mod":
+ if (AuctionBlacklist.addMod(value)) {
+ sendResult(sender, "Added mod to blacklist: " + value);
+ } else {
+ sendError(sender, "Failed to add mod to blacklist");
+ }
+ break;
+ case "nbt":
+ if (AuctionBlacklist.addNBTTag(value)) {
+ sendResult(sender, "Added NBT tag to blacklist: " + value);
+ } else {
+ sendError(sender, "Failed to add NBT tag to blacklist");
+ }
+ break;
+ default:
+ sendError(sender, "Unknown type: " + type + ". Use: item, mod, or nbt");
+ }
+ }
+
+ @SubCommand(
+ desc = "Remove item, mod, or NBT tag from blacklist",
+ usage = "
- "
+ )
+ public void remove(ICommandSender sender, String[] args) throws CommandException {
+ if (args.length < 2) {
+ sendError(sender, "Usage: /cnpc auction blacklist remove
- ");
+ return;
+ }
+
+ String type = args[0].toLowerCase();
+ String value = args[1];
+
+ switch (type) {
+ case "item":
+ if (AuctionBlacklist.removeItem(value)) {
+ sendResult(sender, "Removed item from blacklist: " + value);
+ } else {
+ sendError(sender, "Item not found in blacklist: " + value);
+ }
+ break;
+ case "mod":
+ if (AuctionBlacklist.removeMod(value)) {
+ sendResult(sender, "Removed mod from blacklist: " + value);
+ } else {
+ sendError(sender, "Mod not found in blacklist: " + value);
+ }
+ break;
+ case "nbt":
+ if (AuctionBlacklist.removeNBTTag(value)) {
+ sendResult(sender, "Removed NBT tag from blacklist: " + value);
+ } else {
+ sendError(sender, "NBT tag not found in blacklist: " + value);
+ }
+ break;
+ default:
+ sendError(sender, "Unknown type: " + type + ". Use: item, mod, or nbt");
+ }
+ }
+
+ @SubCommand(
+ desc = "List blacklisted items, mods, or NBT tags",
+ usage = "[item|mod|nbt]"
+ )
+ public void list(ICommandSender sender, String[] args) throws CommandException {
+ String filter = args.length > 0 ? args[0].toLowerCase() : "all";
+
+ if (filter.equals("all") || filter.equals("item")) {
+ List items = AuctionBlacklist.getBlacklistedItems();
+ sendMessage(sender, "\u00A76=== Blacklisted Items (" + items.size() + ") ===");
+ if (items.isEmpty()) {
+ sendMessage(sender, "\u00A77 (none)");
+ } else {
+ for (String item : items) {
+ sendMessage(sender, "\u00A7e " + item);
+ }
+ }
+ }
+
+ if (filter.equals("all") || filter.equals("mod")) {
+ List mods = AuctionBlacklist.getBlacklistedMods();
+ sendMessage(sender, "\u00A76=== Blacklisted Mods (" + mods.size() + ") ===");
+ if (mods.isEmpty()) {
+ sendMessage(sender, "\u00A77 (none)");
+ } else {
+ for (String mod : mods) {
+ sendMessage(sender, "\u00A7e " + mod);
+ }
+ }
+ }
+
+ if (filter.equals("all") || filter.equals("nbt")) {
+ List tags = AuctionBlacklist.getBlacklistedNBTTags();
+ sendMessage(sender, "\u00A76=== Blacklisted NBT Tags (" + tags.size() + ") ===");
+ if (tags.isEmpty()) {
+ sendMessage(sender, "\u00A77 (none)");
+ } else {
+ for (String tag : tags) {
+ sendMessage(sender, "\u00A7e " + tag);
+ }
+ }
+ }
+
+ sendMessage(sender, "\u00A77Note: Soulbound and Profile-Slotbound items are always blocked.");
+ }
+
+ @SubCommand(
+ desc = "Reload blacklist from config"
+ )
+ public void reload(ICommandSender sender, String[] args) throws CommandException {
+ AuctionBlacklist.reload();
+ sendResult(sender, "Blacklist reloaded from config");
+ }
+
+ @SubCommand(
+ desc = "Check if held item is blacklisted",
+ permission = 0
+ )
+ public void check(ICommandSender sender, String[] args) throws CommandException {
+ if (!(sender instanceof EntityPlayer)) {
+ sendError(sender, "This command can only be used by players");
+ return;
+ }
+
+ EntityPlayer player = (EntityPlayer) sender;
+ ItemStack heldItem = player.getHeldItem();
+
+ if (heldItem == null) {
+ sendError(sender, "You are not holding an item");
+ return;
+ }
+
+ String registryName = AuctionBlacklist.getRegistryName(heldItem);
+ sendMessage(sender, "\u00A76=== Blacklist Check ===");
+ sendMessage(sender, "\u00A77Item: \u00A7e" + heldItem.getDisplayName());
+ sendMessage(sender, "\u00A77Registry: \u00A7e" + (registryName != null ? registryName : "unknown"));
+
+ boolean isBlacklisted = AuctionBlacklist.isBlacklisted(heldItem);
+ boolean canBypass = AuctionBlacklist.canBypass(player);
+
+ if (isBlacklisted) {
+ sendMessage(sender, "\u00A7cStatus: BLACKLISTED");
+ if (canBypass) {
+ sendMessage(sender, "\u00A7aYou have bypass permission");
+ }
+ } else {
+ sendMessage(sender, "\u00A7aStatus: ALLOWED");
+ }
+ }
+
+ @Override
+ public List addTabCompletionOptions(ICommandSender sender, String[] args) {
+ if (args.length == 1) {
+ return getListOfStringsMatchingLastWord(args, getAllSubCommandNames());
+ }
+ if (args.length == 2) {
+ String subCmd = args[0].toLowerCase();
+ if (subCmd.equals("add") || subCmd.equals("remove") || subCmd.equals("list")) {
+ return getListOfStringsMatchingLastWord(args, new String[]{"item", "mod", "nbt"});
+ }
+ }
+ return null;
+ }
+}
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..003f58fca
--- /dev/null
+++ b/src/main/java/kamkeel/npcs/controllers/AbilityController.java
@@ -0,0 +1,1487 @@
+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.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 net.minecraft.entity.player.EntityPlayer;
+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.syncAllCustomAbilities();
+ 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;
+
+ 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);
+ 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;
+ }
+ if (changed) {
+ pData.save();
+ }
+ }
+ }
+ }
+
+ customAbilityRevision++;
+ LogWriter.script("Deleted custom ability: " + name);
+ SyncController.syncAllCustomAbilities();
+ 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.syncAllChainedAbilities();
+ 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;
+
+ 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);
+ 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.syncAllChainedAbilities();
+ 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