diff --git a/src/api b/src/api index f9de3f4f3..03be7a5ca 160000 --- a/src/api +++ b/src/api @@ -1 +1 @@ -Subproject commit f9de3f4f326d8e45750d28695a5f212db70bdfca +Subproject commit 03be7a5cac601cd19509df9dc7bac17081aea591 diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java index 2148a239d..3b892335e 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/Ability.java @@ -409,9 +409,26 @@ public abstract class Ability implements IAbility { FieldDef.intField("ability.maxRange", () -> (int) getMaxRange(), v -> setMaxRange(v)).range(1, 100) ).tab("Target")); if (!isTargetingModeLocked()) { - defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class, - this::getTargetingMode, this::setTargetingMode) - .tab("Target").hover("ability.hover.targeting")); + TargetingMode[] allowed = getAllowedTargetingModes(); + if (allowed != null && allowed.length > 0) { + // Build string enum from allowed targeting modes only + String[] allowedKeys = new String[allowed.length]; + for (int i = 0; i < allowed.length; i++) { + allowedKeys[i] = allowed[i].name(); + } + defs.add(FieldDef.stringEnumField("ability.targetingMode", allowedKeys, + () -> this.getTargetingMode().name(), + v -> { + try { this.setTargetingMode(TargetingMode.valueOf(v)); } + catch (Exception ignored) {} + }) + .tab("Target").hover("ability.hover.targeting")); + } else { + // No restrictions - show all modes + defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class, + this::getTargetingMode, this::setTargetingMode) + .tab("Target").hover("ability.hover.targeting")); + } } // Effects tab - Sounds @@ -563,8 +580,12 @@ public abstract class Ability implements IAbility { instance.setEntityIdToFollow(caster.getEntityId()); // For LINE/CONE telegraphs: track target direction during windup + // Only track if movement is NOT locked during windup (locked = NPC can't rotate) if ((telegraphType == TelegraphType.LINE || telegraphType == TelegraphType.CONE) && target != null) { - instance.setTargetEntityId(target.getEntityId()); + if (!lockMovement.locksWindup()) { + instance.setTargetEntityId(target.getEntityId()); + } + // If windup is locked, yaw stays fixed at creation time } } else if (target != null) { // AOE_TARGET abilities: telegraph follows target during windup diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java index ba0962356..e0e5e020a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityCutter.java @@ -113,12 +113,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter { switch (sweepMode) { case SWIPE: + float prevRotation = currentRotation; + currentRotation += sweepSpeed; if (currentRotation > arcAngle / 2.0f) { - signalCompletion(); // Swipe arc complete + // Final sweep — check from prevRotation to end of arc + performSweepDamageRange(caster, world, innerRadius, range, prevRotation, arcAngle / 2.0f); + signalCompletion(); return; } - performSweepDamage(caster, world, innerRadius, range, currentRotation); - currentRotation += sweepSpeed; + // Check entities between previous and current sweep position + performSweepDamageRange(caster, world, innerRadius, range, prevRotation, currentRotation); break; case SPIN: @@ -126,15 +130,23 @@ public class AbilityCutter extends Ability implements IAbilityCutter { signalCompletion(); // Spin duration complete return; } + float prevSpin = currentRotation; currentRotation = (currentRotation + sweepSpeed) % 360.0f; hitEntities.clear(); - performSweepDamage(caster, world, innerRadius, range, currentRotation); + performSweepDamageRange(caster, world, innerRadius, range, prevSpin, currentRotation); break; } } - private void performSweepDamage(EntityLivingBase caster, World world, float minDist, float maxDist, float angleOffset) { - float casterYaw = caster.rotationYaw + angleOffset; + /** + * Check for entities between two sweep angles, ensuring no gaps between ticks. + * For SWIPE mode, this covers the continuous arc from startAngle to endAngle. + */ + private void performSweepDamageRange(EntityLivingBase caster, World world, float minDist, float maxDist, + float startAngle, float endAngle) { + // Calculate the angular range covered this tick + float minAngle = Math.min(startAngle, endAngle); + float maxAngle = Math.max(startAngle, endAngle); AxisAlignedBB searchBox = AxisAlignedBB.getBoundingBox( caster.posX - maxDist, caster.posY - 1, caster.posZ - maxDist, @@ -155,7 +167,7 @@ public class AbilityCutter extends Ability implements IAbilityCutter { double dist = Math.sqrt(dx * dx + dz * dz); if (dist < minDist || dist > maxDist) continue; - if (!isInArc(dx, dz, casterYaw, arcAngle)) continue; + if (!isInSweepRange(dx, dz, caster.rotationYaw, minAngle, maxAngle)) continue; hitEntities.add(entity.getEntityId()); @@ -172,6 +184,16 @@ public class AbilityCutter extends Ability implements IAbilityCutter { } } + /** + * Check if an entity falls within the angular range between two sweep positions. + * This ensures entities at long range can't slip between tick-gaps. + */ + private boolean isInSweepRange(double dx, double dz, float casterYaw, float minAngle, float maxAngle) { + double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); + double entityRelative = normalizeAngle(angleToEntity - casterYaw); + return entityRelative >= minAngle && entityRelative <= maxAngle; + } + private boolean isInArc(double dx, double dz, float casterYaw, float arcWidth) { double angleToEntity = Math.toDegrees(Math.atan2(-dx, dz)); double angleDiff = normalizeAngle(angleToEntity - casterYaw); diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java index fb5d59f0e..6c514a7f0 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityDash.java @@ -92,6 +92,7 @@ public class AbilityDash extends Ability implements IAbilityDash { // Runtime state private transient Vec3 dashDirection; private transient double startX, startY, startZ; + private transient double prevTickX, prevTickZ; private transient DashDirection chosenDirection; public AbilityDash() { @@ -130,6 +131,8 @@ public class AbilityDash extends Ability implements IAbilityDash { startX = caster.posX; startY = caster.posY; startZ = caster.posZ; + prevTickX = caster.posX; + prevTickZ = caster.posZ; // Choose random direction based on mode DashDirection[] directions = dashMode == DashMode.AGGRESSIVE @@ -163,6 +166,22 @@ public class AbilityDash extends Ability implements IAbilityDash { public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, World world, int tick) { if (dashDirection == null) return; + // Stall detection: if entity hasn't moved since last tick, it's stuck against a wall + if (tick > 1) { + double movedThisTick = Math.sqrt( + Math.pow(caster.posX - prevTickX, 2) + + Math.pow(caster.posZ - prevTickZ, 2)); + if (movedThisTick < 0.01) { + caster.motionX = 0; + caster.motionZ = 0; + caster.velocityChanged = true; + signalCompletion(); + return; + } + } + prevTickX = caster.posX; + prevTickZ = caster.posZ; + // Calculate distance traveled double distanceTraveled = Math.sqrt( Math.pow(caster.posX - startX, 2) + diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java index 3db472c1a..ce432e01a 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityHeavyHit.java @@ -6,37 +6,40 @@ import kamkeel.npcs.controllers.data.ability.Ability; import kamkeel.npcs.controllers.data.ability.LockMovementType; import kamkeel.npcs.controllers.data.ability.TargetingMode; import kamkeel.npcs.controllers.data.telegraph.TelegraphType; +import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import noppes.npcs.client.gui.builder.FieldDef; import kamkeel.npcs.controllers.data.ability.gui.AbilityFieldDefs; import noppes.npcs.api.ability.type.IAbilityHeavyHit; -import noppes.npcs.entity.EntityNPCInterface; import java.util.Arrays; import java.util.List; /** - * Heavy Hit ability: Single-target melee attack with optional stun. - * Deals high damage to one target and can stun them. + * Heavy Hit ability: AOE rectangle melee attack in front of the caster. + * Deals high damage to all entities within a rectangular zone and can apply effects. + * Has a LINE telegraph showing the hit area during windup, making it dodgeable. */ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { private float damage = 8.0f; private float knockback = 2.0f; + private float hitLength = 4.0f; // How far in front of the caster the hit reaches + private float hitWidth = 3.0f; // How wide to each side (total width = hitWidth * 2) public AbilityHeavyHit() { this.typeId = "ability.cnpc.heavy_hit"; this.name = "Heavy Hit"; - this.targetingMode = TargetingMode.AGGRO_TARGET; - this.maxRange = 3.0f; + this.targetingMode = TargetingMode.AOE_SELF; + this.maxRange = 5.0f; this.minRange = 0.0f; - this.lockMovement = LockMovementType.NO; + this.lockMovement = LockMovementType.WINDUP; this.cooldownTicks = 0; this.windUpTicks = 30; - this.telegraphType = TelegraphType.POINT; - this.showTelegraph = false; + this.telegraphType = TelegraphType.LINE; + this.showTelegraph = true; this.windUpSound = "random.anvil_use"; this.activeSound = "random.anvil_land"; this.windUpAnimationName = "Ability_HeavyHit_Windup"; @@ -50,22 +53,66 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { @Override public TargetingMode[] getAllowedTargetingModes() { - return new TargetingMode[]{TargetingMode.AGGRO_TARGET}; + return new TargetingMode[]{TargetingMode.AOE_SELF}; + } + + @Override + public float getTelegraphLength() { + return hitLength; + } + + @Override + public float getTelegraphWidth() { + return hitWidth * 2.0f; // Total width (hitWidth is distance to each side) } @Override public void onExecute(EntityLivingBase caster, EntityLivingBase target, World world) { - if (world.isRemote || target == null) { + if (world.isRemote) { signalCompletion(); return; } - // Apply damage with scripted event support - boolean wasHit = applyAbilityDamage(caster, target, damage, knockback); + // Calculate forward and right vectors from caster yaw + float yawRad = (float) Math.toRadians(caster.rotationYaw); + double forwardX = -Math.sin(yawRad); + double forwardZ = Math.cos(yawRad); + double rightX = forwardZ; // perpendicular right + double rightZ = -forwardX; - // Apply effects if hit wasn't cancelled - if (wasHit) { - applyEffects(target); + // Search area: AABB that encompasses the rectangle + float searchDist = Math.max(hitLength, hitWidth) + 1.0f; + @SuppressWarnings("unchecked") + List entities = world.getEntitiesWithinAABBExcludingEntity( + caster, caster.boundingBox.expand(searchDist, 2, searchDist)); + + boolean anyHit = false; + for (Entity entity : entities) { + if (!(entity instanceof EntityLivingBase) || entity == caster) continue; + EntityLivingBase livingTarget = (EntityLivingBase) entity; + + double dx = livingTarget.posX - caster.posX; + double dz = livingTarget.posZ - caster.posZ; + + // Project onto forward direction (must be in front, within hitLength) + double forwardDist = dx * forwardX + dz * forwardZ; + if (forwardDist < 0 || forwardDist > hitLength) continue; + + // Project onto right direction (must be within hitWidth to each side) + double sideDist = dx * rightX + dz * rightZ; + if (Math.abs(sideDist) > hitWidth) continue; + + // Entity is within the rectangle - apply damage + boolean wasHit = applyAbilityDamage(caster, livingTarget, damage, knockback); + if (wasHit) { + applyEffects(livingTarget); + anyHit = true; + } + } + + // Play hit sound even if nothing was hit (the attack still happens) + if (!anyHit) { + world.playSoundAtEntity(caster, "random.anvil_land", 0.5f, 1.2f); } } @@ -80,12 +127,16 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { public void writeTypeNBT(NBTTagCompound nbt) { nbt.setFloat("damage", damage); nbt.setFloat("knockback", knockback); + nbt.setFloat("hitLength", hitLength); + nbt.setFloat("hitWidth", hitWidth); } @Override public void readTypeNBT(NBTTagCompound nbt) { this.damage = nbt.hasKey("damage") ? nbt.getFloat("damage") : 8.0f; this.knockback = nbt.hasKey("knockback") ? nbt.getFloat("knockback") : 2.0f; + this.hitLength = nbt.hasKey("hitLength") ? nbt.getFloat("hitLength") : 4.0f; + this.hitWidth = nbt.hasKey("hitWidth") ? nbt.getFloat("hitWidth") : 3.0f; } // Getters & Setters @@ -105,6 +156,22 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { this.knockback = knockback; } + public float getHitLength() { + return hitLength; + } + + public void setHitLength(float hitLength) { + this.hitLength = hitLength; + } + + public float getHitWidth() { + return hitWidth; + } + + public void setHitWidth(float hitWidth) { + this.hitWidth = hitWidth; + } + @SideOnly(Side.CLIENT) @Override public List getFieldDefinitions() { @@ -113,6 +180,11 @@ public class AbilityHeavyHit extends Ability implements IAbilityHeavyHit { FieldDef.floatField("enchantment.damage", this::getDamage, this::setDamage), FieldDef.floatField("ability.knockback", this::getKnockback, this::setKnockback) ), + FieldDef.section("ability.section.hitZone"), + FieldDef.row( + FieldDef.floatField("ability.hitLength", this::getHitLength, this::setHitLength), + FieldDef.floatField("ability.hitWidth", this::getHitWidth, this::setHitWidth) + ), AbilityFieldDefs.effectsListField("ability.effects", this::getEffects, this::setEffects) ); } diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java index 94381209b..39f1a3ca8 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilitySlam.java @@ -130,9 +130,46 @@ public class AbilitySlam extends Ability implements IAbilitySlam { launchTowardTarget(caster); } + /** + * Calculate the initial vertical velocity needed to reach a target height + * in Minecraft's physics (gravity=0.08, vertical drag=0.98). + * Uses iterative simulation since the drag makes a closed-form solution impractical. + */ + private static double calculateLaunchVelocity(double targetHeight) { + // Binary search for the initial velocity that reaches targetHeight + double lo = 0.0, hi = 10.0; + for (int iter = 0; iter < 30; iter++) { + double mid = (lo + hi) / 2.0; + double maxY = simulateMaxHeight(mid); + if (maxY < targetHeight) { + lo = mid; + } else { + hi = mid; + } + } + return (lo + hi) / 2.0; + } + + /** + * Simulate Minecraft vertical physics to find peak height reached + * with a given initial upward velocity. + */ + private static double simulateMaxHeight(double vy) { + double y = 0; + double maxY = 0; + for (int t = 0; t < 200 && vy > 0; t++) { + y += vy; + vy -= 0.08; // gravity + vy *= 0.98; // vertical drag + if (y > maxY) maxY = y; + } + return maxY; + } + /** * Calculate ballistic arc and launch caster toward target. - * Accounts for Minecraft's drag physics to actually reach the destination. + * leapHeight = exact peak height in blocks above launch point. + * leapSpeed = velocity multiplier (faster motion, same height). */ private void launchTowardTarget(EntityLivingBase caster) { double dx = targetX - caster.posX; @@ -140,11 +177,15 @@ public class AbilitySlam extends Ability implements IAbilitySlam { double dz = targetZ - caster.posZ; double horizontalDist = Math.sqrt(dx * dx + dz * dz); + // Calculate vertical velocity to reach exact leapHeight + double arcHeight = Math.max(1.0, leapHeight); + double vy = calculateLaunchVelocity(arcHeight); + // For AOE_SELF or very close targets, just hop in place if (horizontalDist < 0.5) { caster.motionX = 0; caster.motionZ = 0; - caster.motionY = 0.8 * leapSpeed; + caster.motionY = vy; hasLaunched = true; if (caster instanceof EntityNPCInterface) { ((EntityNPCInterface) caster).setNpcJumpingState(true); @@ -164,8 +205,9 @@ public class AbilitySlam extends Ability implements IAbilitySlam { targetZ = caster.posZ + dz; } - // Choose flight time based on distance - shorter distances = faster - int flightTicks = (int) Math.max(15, Math.min(horizontalDist * 1.5, 30)); + // Choose flight time based on distance, scaled by speed (faster = fewer ticks) + double speedFactor = Math.max(0.1, leapSpeed); + int flightTicks = (int) Math.max(10, Math.min(horizontalDist * 1.5 / speedFactor, 40)); // Minecraft applies drag of 0.91 per tick to horizontal motion in air // Total distance traveled with initial velocity v0 over n ticks: @@ -175,34 +217,16 @@ public class AbilitySlam extends Ability implements IAbilitySlam { double dragPowN = Math.pow(drag, flightTicks); double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN); - // Scale by leap speed - vHorizontal *= leapSpeed; + // Speed scales horizontal velocity to cover ground faster + vHorizontal *= speedFactor; - // Vertical velocity calculation: - // Minecraft gravity is 0.08 per tick, with 0.98 drag on vertical motion - // For a nice arc, we want to peak roughly in the middle of the flight - double gravity = 0.08; - double verticalDrag = 0.98; - - // Calculate required upward velocity to create a nice arc and land at target height - // Peak height should be proportional to horizontal distance for visual appeal - double arcHeight = Math.max(1.0, leapHeight) * leapSpeed; - - // Approximate the required initial vertical velocity - // Account for gravity and drag - use a simplified model - double peakTicks = flightTicks * 0.4; // Peak around 40% through flight - double vy = (arcHeight * 2.0 / peakTicks) + (gravity * peakTicks * 0.5); - - // Adjust for height difference + // Adjust vertical velocity for height difference between start and target if (dy > 0) { vy += dy / flightTicks * 1.5; // Going up - need more velocity } else if (dy < 0) { vy += dy / flightTicks * 0.3; // Going down - gravity helps } - // Ensure minimum upward velocity for visible jump - vy = Math.max(vy, 0.6 * leapSpeed); - // Normalize horizontal direction and apply velocity double dirX = dx / horizontalDist; double dirZ = dz / horizontalDist; @@ -221,7 +245,6 @@ public class AbilitySlam extends Ability implements IAbilitySlam { float targetYaw = (float) (Math.atan2(-dx, dz) * 180.0D / Math.PI); caster.rotationYaw = targetYaw; caster.rotationYawHead = targetYaw; - } @Override @@ -395,10 +418,14 @@ public class AbilitySlam extends Ability implements IAbilitySlam { double dz = tz - npc.posZ; double horizontalDist = Math.sqrt(dx * dx + dz * dz); + // Calculate vertical velocity for exact leapHeight + double arcHeight = Math.max(1.0, leapHeight); + double vy = calculateLaunchVelocity(arcHeight); + if (horizontalDist < 0.5) { previewVelX = 0; previewVelZ = 0; - previewVelY = 0.8 * leapSpeed; + previewVelY = vy; } else { if (horizontalDist > maxRange) { double scale = maxRange / horizontalDist; @@ -407,15 +434,11 @@ public class AbilitySlam extends Ability implements IAbilitySlam { horizontalDist = maxRange; } - int flightTicks = (int) Math.max(15, Math.min(horizontalDist * 1.5, 30)); + double speedFactor = Math.max(0.1, leapSpeed); + int flightTicks = (int) Math.max(10, Math.min(horizontalDist * 1.5 / speedFactor, 40)); double drag = 0.91; double dragPowN = Math.pow(drag, flightTicks); - double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN) * leapSpeed; - - double arcHeight = Math.max(1.0, leapHeight) * leapSpeed; - double peakTicks = flightTicks * 0.4; - double vy = (arcHeight * 2.0 / peakTicks) + (0.08 * peakTicks * 0.5); - vy = Math.max(vy, 0.6 * leapSpeed); + double vHorizontal = horizontalDist * (1.0 - drag) / (1.0 - dragPowN) * speedFactor; double dirX = dx / horizontalDist; double dirZ = dz / horizontalDist; diff --git a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java index 6c92304e2..aaa6041f4 100644 --- a/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java +++ b/src/main/java/kamkeel/npcs/controllers/data/ability/type/AbilityVortex.java @@ -138,7 +138,7 @@ public class AbilityVortex extends Ability implements IAbilityVortex { double dz = destZ - entity.posZ; double dist = Math.sqrt(dx * dx + dy * dy + dz * dz); - if (dist <= 1.0f) { + if (dist <= 1.5f) { getPulledEntities().remove(uuid); onTargetArrived(caster, entity, world); continue; @@ -146,7 +146,10 @@ public class AbilityVortex extends Ability implements IAbilityVortex { anyStillPulling = true; - double factor = pullStrength / dist; + // Clamp speed to never exceed half the remaining distance, preventing overshoot/slingshot + double maxSpeed = dist * 0.5; + double effectiveSpeed = Math.min(pullStrength, maxSpeed); + double factor = effectiveSpeed / dist; double nextX = dx * factor; double nextY = dy * factor * 0.5; double nextZ = dz * factor; diff --git a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java index 57f99e1c8..10dd0d953 100644 --- a/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java +++ b/src/main/java/kamkeel/npcs/entity/EntityAbilityProjectile.java @@ -192,6 +192,19 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA // Skip lifetime/distance checks in preview mode if (!previewMode) { + // Failsafe: if owner entity is gone, dead, or NPC was killed/reset, self-destruct + if (ownerEntityId >= 0 && ticksExisted > 5) { + Entity owner = worldObj.getEntityByID(ownerEntityId); + if (owner == null || owner.isDead) { + this.setDead(); + return; + } + if (owner instanceof EntityNPCInterface && ((EntityNPCInterface) owner).isKilled()) { + this.setDead(); + return; + } + } + // Set death time on first tick if not already set (handles chunk load/unload) if (deathWorldTime < 0 && worldObj != null) { deathWorldTime = worldObj.getTotalWorldTime() + maxLifetime; @@ -392,6 +405,10 @@ public abstract class EntityAbilityProjectile extends Entity implements IEntityA // ==================== ENTITY HELPERS ==================== + public int getOwnerEntityId() { + return ownerEntityId; + } + protected Entity getOwner() { // In preview mode, use direct reference (no world lookup) if (previewMode && previewOwner != null) { diff --git a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java index 60c3561b3..1e97227a9 100644 --- a/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java +++ b/src/main/java/noppes/npcs/client/gui/advanced/SubGuiAbilityConfig.java @@ -281,11 +281,9 @@ public class SubGuiAbilityConfig extends SubGuiInterface implements ITextfieldLi // Declarative field handling (effects list, booleans, enums, sub-guis, clear buttons) if (builder.handleButtonEvent(id, guibutton)) { - // SUB_GUI needs special handling: open the sub-gui - FieldDef subGuiDef = builder.getActiveSubGuiField(); - if (subGuiDef != null && subGuiDef.getSubGuiFactory() != null) { - setSubGui(subGuiDef.getSubGuiFactory().get()); - } else { + // SUB_GUI fields are opened directly by the builder via setSubGuiWithResult(). + // Only rebuild if no sub-gui was opened (e.g. boolean toggle, enum change). + if (!hasSubGui()) { initGui(); } return; diff --git a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java index 63f188d44..6d9ee58ec 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java +++ b/src/main/java/noppes/npcs/client/gui/builder/FieldDef.java @@ -297,4 +297,55 @@ public class FieldDef { public FieldDef getLeftChild() { return leftChild; } public FieldDef getRightChild() { return rightChild; } + // ═══════════════════════════════════════════════════════════════════ + // LIST MANIPULATION (for mod injection) + // ═══════════════════════════════════════════════════════════════════ + + /** + * Insert a field before the first field matching the target label. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to insert before + * @param newField The field to insert + * @return true if the target was found and the field was inserted + */ + public static boolean insertBefore(java.util.List fields, String targetLabel, FieldDef newField) { + for (int i = 0; i < fields.size(); i++) { + if (matchesLabel(fields.get(i), targetLabel)) { + fields.add(i, newField); + return true; + } + } + return false; + } + + /** + * Insert a field after the first field matching the target label. + * Searches top-level labels and ROW children. + * + * @param fields The field list to modify + * @param targetLabel The label of the field to insert after + * @param newField The field to insert + * @return true if the target was found and the field was inserted + */ + public static boolean insertAfter(java.util.List fields, String targetLabel, FieldDef newField) { + for (int i = 0; i < fields.size(); i++) { + if (matchesLabel(fields.get(i), targetLabel)) { + fields.add(i + 1, newField); + return true; + } + } + return false; + } + + private static boolean matchesLabel(FieldDef def, String targetLabel) { + if (targetLabel.equals(def.label)) return true; + if (def.type == FieldType.ROW) { + if (def.leftChild != null && targetLabel.equals(def.leftChild.label)) return true; + if (def.rightChild != null && targetLabel.equals(def.rightChild.label)) return true; + } + return false; + } + } diff --git a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java index 43a3956c1..42e117ecf 100644 --- a/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java +++ b/src/main/java/noppes/npcs/client/gui/builder/GuiFieldBuilder.java @@ -333,11 +333,13 @@ public class GuiFieldBuilder { // EVENT HANDLING // ═══════════════════════════════════════════════════════════════════ - private FieldDef activeSubGuiField; - /** * Handles button events for declarative fields. * Call from parent GUI's buttonEvent(). Returns true if the event was handled. + *

+ * For SUB_GUI fields, the sub-gui is opened directly via {@code parent.setSubGuiWithResult()}, + * so the result handler survives initGui() rebuilds. After this returns true, check + * {@code parent.hasSubGui()} to determine if initGui() should be called. */ @SuppressWarnings({"unchecked", "rawtypes"}) public boolean handleButtonEvent(int buttonId, GuiButton button) { @@ -374,7 +376,13 @@ public class GuiFieldBuilder { return true; } case SUB_GUI: - activeSubGuiField = def; + if (def.getSubGuiFactory() != null) { + parent.setSubGuiWithResult(def.getSubGuiFactory().get(), sub -> { + if (def.getSubGuiResultHandler() != null) { + def.getSubGuiResultHandler().accept(sub); + } + }); + } return true; default: return false; @@ -406,32 +414,16 @@ public class GuiFieldBuilder { /** * Handles sub-gui close events. Call from parent GUI's subGuiClosed(). - * Returns true if the event was handled (activeSubGuiField was set). + *

+ * Note: SUB_GUI fields opened via handleButtonEvent use + * {@code parent.setSubGuiWithResult()}, so their results are handled + * automatically by {@code GuiNPCInterface.closeSubGui()}. This method + * only handles sub-guis opened through other means. */ public boolean handleSubGuiClosed(SubGuiInterface subgui) { - if (activeSubGuiField != null) { - FieldDef def = activeSubGuiField; - activeSubGuiField = null; - if (def.getSubGuiResultHandler() != null) { - def.getSubGuiResultHandler().accept(subgui); - } - return true; - } return false; } - /** - * Returns the FieldDef for the currently active sub-gui, or null. - * After handleButtonEvent returns true for a SUB_GUI field, the parent - * should check this and call setSubGui(def.getSubGuiFactory().get()). - */ - public FieldDef getActiveSubGuiField() { return activeSubGuiField; } - - /** - * Clears the active sub-gui field tracking. - */ - public void clearActiveSubGuiField() { activeSubGuiField = null; } - // ═══════════════════════════════════════════════════════════════════ // GETTERS // ═══════════════════════════════════════════════════════════════════ diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java index 4ddd820c0..06f74bffe 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiNPCInterface.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; import java.util.function.Supplier; public abstract class GuiNPCInterface extends GuiScreen { @@ -52,6 +53,7 @@ public abstract class GuiNPCInterface extends GuiScreen { public Supplier closeOnEscSupplier = null; public int guiLeft, guiTop, xSize, ySize; private SubGuiInterface subgui; + private Consumer pendingSubGuiResult; public int mouseX, mouseY, mouseScroll; public float bgScale = 1; public float bgScaleX = 1; @@ -519,7 +521,21 @@ public abstract class GuiNPCInterface extends GuiScreen { initGui(); } + /** + * Open a sub-gui with a result handler that will be called when the sub-gui closes. + * The handler survives initGui() rebuilds since it lives on the parent, not the builder. + */ + public void setSubGuiWithResult(SubGuiInterface gui, Consumer resultHandler) { + this.pendingSubGuiResult = resultHandler; + setSubGui(gui); + } + public void closeSubGui(SubGuiInterface gui) { + if (pendingSubGuiResult != null) { + Consumer handler = pendingSubGuiResult; + pendingSubGuiResult = null; + handler.accept(gui); + } subgui = null; initGui(); }