////////////////////////////////////////////////////////////////////////////////
//
//  Siege Catapult - Fires the Projectile
//  os_fire_cat
//  by Don Anderson
//  dandersonru@msn.com
//
////////////////////////////////////////////////////////////////////////////////

#include "os_inc"

void main()
{
    object oCat = OBJECT_SELF;
    object oArea = GetArea(oCat);
    object oPC = GetPCSpeaker();
    vector vCurrentPosition = GetPosition(oCat);
    float fCurrentFacing = GetFacing(oCat);

    //Calculate the target location.
    float fRange = GetLocalFloat(oCat, "RANGE");

    if (fCurrentFacing > 360.0)
    {
        fCurrentFacing = 720 - fCurrentFacing;
    }

    int nRX = Random(2);
    int nRY = Random(2);
    int nRN = Random(2);

    //Positive Error
    if(nRN == 0) nRX = nRX;
    //Negative Error
    if(nRN == 1) nRX = nRX * (-1);
    //Positive Error
    if(nRN == 0) nRY = nRY;
    //Negative Error
    if(nRN == 1) nRY = nRY * (-1);

    //Total Range Error for Location Target
    float fError = SIEGE_ERRANT * fRange * d4(1);

    vector vDelta;

    //On Target
    if (fError <= 2.0)
    {
        vDelta.x = cos(fCurrentFacing) * fRange;
        vDelta.y = sin(fCurrentFacing) * fRange;
        AssignCommand(oCat, SpeakString("Projectile away and on target!"));
    }
    //A little off Target
    else
    {
        vDelta.x = cos(fCurrentFacing) * (fRange + (fError * IntToFloat(nRX)));
        vDelta.y = sin(fCurrentFacing) * (fRange + (fError * IntToFloat(nRY)));
        AssignCommand(oCat, SpeakString("Projectile away and a little off target!"));
    }

    vector vImpact;
    vImpact.x = vCurrentPosition.x + vDelta.x;
    vImpact.y = vCurrentPosition.y + vDelta.y;

    location lLoc = Location(oArea, vImpact, fCurrentFacing);
    float fImpactDelay = fRange/18;

    //Play the Catapult's VFX
    effect eImpact;
    effect eBump;
    int nSpell;
    int nAmmo;
    float fRadius;

    PlaySound("cb_sh_catapult");

    if(GetLocalInt(oCat,"LOADED") == 1)
    {
      //Fire was Loaded
      if (GetLocalInt(oCat,"AMMOTYPE") == FIRE)
      {
        eImpact = EffectVisualEffect(VFX_FNF_FIREBALL);
        eBump   = EffectVisualEffect(VFX_FNF_SCREEN_BUMP);
        nSpell  = SPELL_FIREBALL;
        fRadius = FIRE_RADIUS;
        nAmmo   = FIRE;
        FireBlast(lLoc,fImpactDelay,eImpact,eBump,nSpell,fRadius,nAmmo);
        DeleteLocalInt(oCat,"AMMOTYPE");
        SetLocalInt(oCat,"LOADED",0);
      }

      //Acid was Loaded
      if (GetLocalInt(oCat,"AMMOTYPE") == ACID)
      {
        eImpact = EffectVisualEffect(VFX_FNF_GAS_EXPLOSION_ACID);
        eBump   = EffectVisualEffect(VFX_FNF_SCREEN_BUMP);
        nSpell  = SPELL_ACID_FOG;
        fRadius = ACID_RADIUS;
        nAmmo   = ACID;
        AcidBlast(lLoc,fImpactDelay,eImpact,eBump,nSpell,fRadius,nAmmo);
        DeleteLocalInt(oCat,"AMMOTYPE");
        SetLocalInt(oCat,"LOADED",0);
      }
    }
}