@name AAGun
@inputs Gun:entity Plate:entity Active
@outputs 
@persist Target:entity
@trigger 

if (first()) {
    
    function number leadTime(MuzzleVelocity, [RelativeVelocity DeltaPos]:vector)
    {
        	
        		#Returns the time it takes for a gun to shoot at some target given:
        		#-The muzzle velocity of the gun
        		#-The relative velocity between the target and the gun (Target:vel() - Gun:vel())
        		#-The relative position between the target and the gun (Target:pos() - Gun:pos())
        	
        	
        	local A = RelativeVelocity:dot(RelativeVelocity) - MuzzleVelocity^2
        	local B = 2 * RelativeVelocity:dot(DeltaPos)
        	local C = DeltaPos:dot(DeltaPos)
        
        	local Det = B^2 - 4*A*C
        	
        	return Det > 0 ? (2 * C / (sqrt(Det)-B)) : -1 #Returns negative 1 if "there is no solution"
    }
    
    function vector leadPos(MuzzleVelocity, [RelativeVelocity DeltaPos TargetVel]:vector)
    {
        	#Returns the position in front of a target, in a local sort of sense (same sense as like Target:vel()), given the parameters above
        	#print(TargetVel)
        	local Time = leadTime(MuzzleVelocity, RelativeVelocity, DeltaPos)
        	if(Time >= 0) #If it's negative then we didn't get a solution
        	{
        		return (TargetVel * Time)
        	}
        return vec()
    }
    runOnTick(1)
    
    holoCreate(1, vec(), vec(50))
    holoDisableShading(1, 1)
    holoAlpha(1, 15)
}


if (Active) {
    if (!Target) {
        Target = findPlayerByName("Metacore")
    }

    local TP = Target:vehicle():parent():parent()
    local GP = Gun:toWorld(vec(65, 0, 0))
    
    local TargetLead = leadPos(fromUnit("m/s", 936.2), TP:vel() - Gun:vel(), TP:pos() - GP, TP:vel())
    local TargetPos = TP:pos() + TargetLead#*1.015
    
    setName(TargetLead:toString())
    
    Plate:setAng( quat((TargetPos - GP):toAngle()):toAngle() )
    Plate:propFreeze(1)
    
    holoPos(1, TargetPos)
}
#print(TargetLead)

#Torque = Gun:toLocalAxis(rotationVector(quat((TargetPos - Gun:pos()):toAngle()) / quat(Gun)))
#Gun:applyTorque((Torque*1000 - Gun:angVelVector()*20) * GunI)
