@name E2 Pathfinding Chair
@persist Path:array CurNode Pos:vector Going Chair:entity
@trigger PathClk

#include "lib/path/astar"
#include "e2shared/graph_gm_construct"
runOnChat(1)

# Start ambient/energy/whiteflash.wav
# Pass Node ambient/energy/ion_cannon_shot1-3.wav
# Loop ambient/energy/force_field_loop1.wav
# Stop ambient/energy/powerdown2.wav
if (first()) {
    setGraph(Graph)
    Chair=entity():isWeldedTo()
}

if (!Going & chatClk(Chair:driver())) {
    local Command=Chair:driver():lastSaid():explode(" ")
    if (Command[1,string]=="goto") {
        local Target=findPlayerByName(Command[2,string])
        local Pos=Target:pos()+Target:aabbSize()*vec(0,0,0.5)
        Chair:printColorDriver(vec(255,255,0),"[sChair] ",vec(255),"Finding node near ",vec(0,255,0),Target:name())
        local TargetNode=""
        local StartNode=""
        local TargetDist=9e99
        local StartDist=9e99
        foreach(I,V:table=Graph) {
            local Ray=rangerOffset(V["Pos",vector],Pos)
            if (Ray:entity()==Target & Ray:distance()<TargetDist) {
                TargetNode=V["Name",string]
                TargetDist=Ray:distance()
            }
        }
        
        foreach(I,V:table=Graph) {
            local Ray=rangerOffset(Chair:pos(),V["Pos",vector])
            if (Ray:entity()==Chair & Ray:distance()<StartDist) {
                StartNode=V["Name",string]
                StartDist=Ray:distance()
            }
        }
        Chair:printColorDriver(vec(255,255,0),"[sChair] ",vec(255),"End Node Status: ",vec(255),TargetNode ? "Linked." : "No node found.")
        Chair:printColorDriver(vec(255,255,0),"[sChair] ",vec(255),"Start Node Status: ",vec(255),StartNode ? "Linked." : "No node found.")
        
        if (StartNode & TargetNode) {
            Chair:soundPlay(0,0,"buttons/bell1.wav")
            Going=1
            Chair:printColorDriver(vec(255,255,0),"[sChair] ",vec(255),"Building path from ",vec(0,255,0),StartNode,vec(255)," to ",vec(0,255,0),TargetNode,vec(255),".")
            path(StartNode,TargetNode,25)
        }
    }
}

if (clk("PathClk")) {
    Chair:printColorDriver(vec(255,255,0),"[sChair] ",vec(0,255,0),"Path completed.")
    Chair:soundPlay(1,0,"ambient/energy/whiteflash.wav")
    Chair:propNotSolid(1)
    Path=PathClk["Path",array]
    Pos=Chair:pos()
    Ang=Chair:angles()
    CurNode=0
    timer("Go",1)
}

if (clk("Go") & CurNode<=Path:count()) {
    local TargetPos=Graph[Path[CurNode+1,string],table]["Pos",vector]
    Ang=(TargetPos-Pos):toAngle()*ang(0,1,1)
    local RayForward=rangerOffset(5,Pos,(Ang+ang(45,0,0)):forward())
    Ang+=(TargetPos-RayForward:pos()):toAngle()*ang(1,0,0)
    Pos=Pos+Ang:forward()*6
    Pos=rangerOffset(5,Pos,vec(0,0,-1)):pos()
    
    print(_HUD_PRINTCENTER,toString(Pos))
    if (Pos:distance(TargetPos)<12) {
        CurNode++
    }
    
    Chair:setPos(Pos+vec(0,0,15))
    Chair:setAng(Ang)
    
    timer("Go",100)
}









