@name Tank Turret v1
@inputs  [Pod Cam]:wirelink [Gun Chair Base]:entity Active 
@persist Elevation Depression Yaw RotateSpeed FOV LocalVel
@persist CamOffset:vector
@outputs [Inertia Hold]:angle CamL:entity User:entity
@persist Active Mouse2 
@persist CamDist GunMovement
runOnTick(1)

if(first() || dupefinished()){
    Elevation = 20
    Depression = 5
    Yaw = 180
    RotateSpeed = 10
    GunMovement = 1
    CamOffset = vec(0,0,150)
    CamDist = 250
    
    holoCreate(1)
    holoAlpha(1,0)
    
    Hold = entity():toLocal(Gun:angles())
    Inertia = shiftL(ang(Gun:inertia()))
}
                                         
if (~Active) {
    FOV = 90
} 

if (Active) {
    Position = Base:pos() + CamOffset
    Cam["FOV",number] = FOV
    Cam["Position",vector] = Position
    
    if (~Active) {
        Gun:soundPlay(1,0,"acf_extra/vehiclefx/trans/gearwhine2.wav")
        soundPitch(1,0)
        
        Cam["Activated",number] = 1
        Cam["Parent",entity] = entity()
        Cam["Distance",number] = CamDist
        
        User = Chair:driver()
        
        rangerFilter(Gun)
        rangerFilter(entity():getConstraints())
        rangerPersist(1)
        
        Inertia = shiftL(ang(Gun:inertia()))
    }
    
    holoPos(1,rangerOffset(9999999999,Gun:pos()+Gun:forward()*100,Gun:forward()):position())
    
    Mouse2 = User:keyAttack2()
    if (Mouse2 & $Mouse2){
        Hold = entity():toLocal(Gun:angles())
    }
    Angle = Chair:toLocal(User:eyeAngles())
    Ranger = rangerOffset(9999999999,Position,Angle:forward())
    GunAng = entity():toWorld(Hold)*Mouse2+(Ranger:pos() - Gun:pos()):toAngle()*!Mouse2
    
    LocalVel = entity():toLocal(Gun:angles()):yaw()
    soundPitch(1,(abs($LocalVel)>0.3)*80)
} 
else{
    soundPitch(1,0)
    if (~Active) {
        Hold = entity():toLocal(Gun:angles())
    }
    GunAng = entity():toWorld(Hold)
}

Force = Gun:toWorld(clamp(Gun:toLocal(GunAng),ang(-RotateSpeed),ang(RotateSpeed)))
Clamped = clamp(entity():toLocal(Force),ang(-Elevation,-Yaw,-1),ang(Depression,Yaw,1))
LocalToGun = Gun:toLocal(entity():toWorld(Clamped))
Gun:applyAngForce((LocalToGun * 250 - Gun:angVel() * 47 + entity():angVel() * 47 * (abs(Gun:toLocal(GunAng):yaw())>5)*GunMovement) * Inertia)
