Volver al índice

src/main/java/ar/com/companeros/horror/CeilingPursuit.java

package ar.com.companeros.horror;

import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;

/** Trepada, apoyos superiores y caída físicos. Búsqueda local acotada, sin cargar chunks ni consultar IA. */
final class CeilingPursuit {
    static final float HEIGHT=1.85F;
    private enum Phase { IDLE, CLIMB, CEILING, LEAP, SPIDER }
    private final ParasiteEntity body;
    private Phase phase=Phase.IDLE;
    private final ArrayDeque<BlockPos> route=new ArrayDeque<>();
    private BlockPos anchor;
    private UUID target;
    private long started, nextAttempt;
    private boolean originalNoGravity;
    CeilingPursuit(ParasiteEntity body) { this.body=body; }
    int flags() { return phase==Phase.CEILING ? 8 : phase==Phase.LEAP ? 16 : phase==Phase.CLIMB ? 1 : phase==Phase.SPIDER ? 32 : 0; }
    boolean compactRequired() { return phase!=Phase.IDLE; }
    boolean savedNoGravity() { return phase==Phase.IDLE ? body.isNoGravity() : originalNoGravity; }

    boolean tick(LivingEntity prey, boolean allowed) {
        return tick(prey,allowed,false);
    }
    boolean tick(LivingEntity prey, boolean allowed, boolean presenting) {
        long now=body.level().getGameTime();
        // Hablar no suelta los apoyos ni reinicia la maniobra. Validar al oyente y el techo cada tick.
        if (presenting && phase==Phase.CEILING && prey!=null && prey.isAlive()
                && prey.getUUID().equals(target) && supported(anchor) && !body.isInWater() && !body.isInLava()) {
            body.getNavigation().stop(); body.setDeltaMovement(Vec3.ZERO);
            body.getLookControl().setLookAt(prey,30,30); started=now; return true;
        }
        if (!allowed || prey==null || body.getMutationStage()<3 || body.isInWater() || body.isInLava()
                || phase!=Phase.IDLE && !prey.getUUID().equals(target)) { cancel(); return false; }
        if (phase==Phase.IDLE) {
            if (now<nextAttempt || body.tickCount%40!=0 || !body.onGround()
                    || body.distanceToSqr(prey)<49 || body.distanceToSqr(prey)>28*28) return false;
            nextAttempt=now+200;
            if (!plan(prey)) return false;
            originalNoGravity=body.isNoGravity(); phase=Phase.CLIMB; started=now; target=prey.getUUID();
            body.getNavigation().stop(); body.setNoGravity(true);
        }
        // Tras tocar suelo continúa la ruta normal, conservando el cuerpo y la marcha en cuatro apoyos.
        if(phase==Phase.SPIDER) {
            boolean chosen=body.hasChosenBodyPosture();
            boolean differentPose=chosen && body.getBodyPosture()!=ParasiteEntity.BodyPosture.ALL_FOURS;
            boolean openSprint=!chosen && now-started>60 && now%20==0 && body.distanceToSqr(prey)>100
                && ParasiteClearance.fits(body.level(),body,body.position(),body.getStandingHeight());
            if(differentPose || openSprint || body.horizontalCollision || !body.onGround() && body.getDeltaMovement().y>0) cancel();
            return false;
        }
        body.getLookControl().setLookAt(prey,30,30);
        if (now-started>240) { cancel(); return false; }
        if (phase==Phase.CLIMB) {
            double feet=anchor.getY()-HEIGHT-.025;
            if (!supported(anchor) || body.getY()<feet-.25 && !wallBeside(body.position())) { cancel(); return false; }
            // Esperar la compresión gradual antes de acercarse a la cara inferior del techo.
            if (body.getBbHeight()>HEIGHT+.01) { body.setDeltaMovement(Vec3.ZERO); return true; }
            Vec3 goal=new Vec3(anchor.getX()+.5,feet,anchor.getZ()+.5);
            Vec3 delta=goal.subtract(body.position());
            if (delta.lengthSqr()<.025) { phase=Phase.CEILING; body.setDeltaMovement(Vec3.ZERO); }
            else body.setDeltaMovement(limit(delta,.18));
            return true;
        }
        if (phase==Phase.CEILING) {
            if (!supported(anchor)) { cancel(); return false; }
            double horizontal=Math.hypot(prey.getX()-body.getX(),prey.getZ()-body.getZ());
            if (horizontal<=5.5 && body.getY()>prey.getY()+1.25 && body.clearBodySight(prey)) {
                phase=Phase.LEAP; body.setNoGravity(originalNoGravity);
                Vec3 toward=new Vec3(prey.getX()-body.getX(),0,prey.getZ()-body.getZ());
                Vec3 horizontalJump=limit(toward,.48);
                body.setDeltaMovement(horizontalJump.x,-.18,horizontalJump.z);
                body.signalPounce(); nextAttempt=now+600; return true;
            }
            while (!route.isEmpty() && body.position().distanceToSqr(feet(route.peekFirst()))<.07) {
                anchor=route.removeFirst();
            }
            if (route.isEmpty()) { cancel(); return false; }
            BlockPos next=route.peekFirst();
            if (!supported(next) || !ParasiteClearance.clearSegment(body.level(),body,body.position(),feet(next),HEIGHT)) {
                cancel(); return false;
            }
            body.setDeltaMovement(limit(feet(next).subtract(body.position()),.24));
            return true;
        }
        if (body.onGround() || body.verticalCollision && body.getDeltaMovement().y>=0) {
            body.setNoGravity(originalNoGravity); phase=Phase.SPIDER; started=now; return false;
        }
        // La caída conserva su velocidad y gravedad vanilla; no se corrige la posición hacia la presa.
        return true;
    }

    // Grafo de caras inferiores contiguas: como máximo192 nodos y16 bloques desde el arranque.
    private boolean plan(LivingEntity prey) {
        Level level=body.level(); BlockPos origin=body.blockPosition();
        if (!wallBeside(body.position())) return false;
        BlockPos start=null;
        for(int y=origin.getY()+3;y<=origin.getY()+8;y++) {
            BlockPos candidate=new BlockPos(origin.getX(),y,origin.getZ());
            if(supported(candidate)) { start=candidate; break; }
        }
        if(start==null || feet(start).y<=prey.getY()+1.25) return false;
        var queue=new ArrayDeque<BlockPos>(); var parent=new HashMap<BlockPos,BlockPos>();
        queue.add(start); parent.put(start,start); BlockPos goal=null;
        while(!queue.isEmpty() && parent.size()<=192) {
            BlockPos point=queue.removeFirst();
            if(Math.hypot(point.getX()+.5-prey.getX(),point.getZ()+.5-prey.getZ())<=4.5) { goal=point; break; }
            for(Direction direction:List.of(Direction.NORTH,Direction.SOUTH,Direction.WEST,Direction.EAST)) {
                BlockPos next=point.relative(direction);
                if(parent.containsKey(next) || Math.abs(next.getX()-start.getX())>16 || Math.abs(next.getZ()-start.getZ())>16
                        || !supported(next) || !ParasiteClearance.clearSegment(level,body,feet(point),feet(next),HEIGHT)) continue;
                parent.put(next,point); queue.addLast(next);
                if(parent.size()>=192) break;
            }
        }
        if(goal==null) return false;
        route.clear();
        for(BlockPos point=goal;!point.equals(start);point=parent.get(point)) route.addFirst(point);
        if(route.isEmpty()) return false;
        anchor=start; return true;
    }
    private Vec3 feet(BlockPos ceiling) {
        return new Vec3(ceiling.getX()+.5,ceiling.getY()-HEIGHT-.025,ceiling.getZ()+.5);
    }
    private boolean supported(BlockPos ceiling) {
        Level level=body.level();
        return level.hasChunkAt(ceiling) && level.getBlockState(ceiling).isFaceSturdy(level,ceiling,Direction.DOWN)
            && ParasiteClearance.fits(level,body,feet(ceiling),HEIGHT);
    }
    private boolean wallBeside(Vec3 position) {
        Vec3 center=position.add(0,.4,0);
        for(Direction direction:List.of(Direction.NORTH,Direction.SOUTH,Direction.WEST,Direction.EAST)) {
            Vec3 end=center.add(direction.getStepX()*.8,0,direction.getStepZ()*.8);
            if(body.level().clip(new ClipContext(center,end,ClipContext.Block.COLLIDER,ClipContext.Fluid.NONE,body)).getType()==HitResult.Type.BLOCK) return true;
        }
        return false;
    }
    private static Vec3 limit(Vec3 delta,double maximum) { return delta.lengthSqr()>maximum*maximum ? delta.normalize().scale(maximum) : delta; }
    void cancel() {
        if(phase!=Phase.IDLE) { body.setNoGravity(originalNoGravity); nextAttempt=Math.max(nextAttempt,body.level().getGameTime()+200); }
        phase=Phase.IDLE; route.clear(); anchor=null; target=null;
    }
}