#@name mech rewrite
@inputs 
@outputs 
@persist DownVec:vector
@trigger none

if (first()) {
    function table entity:newLeg( Loc:vector, GrdH, StpH, VelD, Rate ) {
        return table(
            "Ent" = This,
            "Status" = "Check",
            "Loc" = Loc,
            "GrdH" = GrdH,
            "StpH" = StpH,
            "VelD" = VelD,
            "Rate" = Rate
        )
    }
    
    function table:checkLeg() {
        local Ranger = rangerOffset(250, This["Ent", entity]:toWorld(This["Loc", vector]) + This["Ent", entity]:vel():setZ(0) / This["VelD", number], DownVec)
        if (Ranger:hit()) {
            This["HoldC", vector] = Ranger:position() + Ranger:hitNormal() * This["GrdH", number]
            local Distance = This["PointC", vector]:distance(This["Output", vector])
            
            if (Distance > 25) {
                This["PointA", vector] = This["Output", vector]
                This["PointB", vector] = mix(This["HoldC", vector], This["PointA", vector], 0.33) + vec(0, 0, Distance / This["StepH", number])
                This["HoldC", vector] = This["Ent", entity]:toLocal(This["HoldC", vector]):setZ(0)
                This["Status", string] = "Run"
            }  
        }
    }
    
    function table:runLeg() {        
        local Ranger = rangerOffset(250, This["Ent", entity]:toWorld(This["HoldC", vector]), DownVec)
        
        This["Time", number] = min(This["Time", number] + 0.2, 1)
        This["PointC", vector] = Ranger:position() + Ranger:hitNormal() * This["GrdH", number]
        This["Output", vector] = mix(
            mix(This["PointC", vector], This["PointB", vector], This["Time", number]),
            mix(This["PointB", vector], This["PointA", vector], This["Time", number]),
            This["Time", number])

        if (This["Time", number] >= 1) {
            This["Time", number] = 0
            This["Status", string] = "Check"
            #This["FootEnt", entity]:soundPlay(This["idx", number] + "stepdown", 0, "npc/dog/dog_footstep"+randint(1,4)+".wav")
        }
    }
}

#[    function table:leg_run() {
        This["Iterate", number] = This["Iterate", number] + 0.2
        
        This["PointC", vector] = rangerOffset(500, This["Entity", entity]:toWorld(This["HoldC", vector]), vec(0,0,-1)):position()
        This["Output", vector] = mix(
            mix(This["PointC", vector], This["PointB", vector], This["Iterate", number]),
            mix(This["PointB", vector], This["PointA", vector], This["Iterate", number]),
            This["Iterate", number])

        if (This["Iterate", number] >= 1) {
            This["Iterate", number] = 0
            This["Status", string] = "Check"
            #This["FootEnt", entity]:soundPlay(This["idx", number] + "stepdown", 0, "npc/dog/dog_footstep"+randint(1,4)+".wav")
        }
    } 
    ]#
