//
// Copyright(C) 2014-2015 Samuel Villarreal
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// DESCRIPTION:
//      Weapon Actions
//

#include "scripts/animations.txt"

#include "scripts/Q2/Debug.cs"
#include "scripts/Q2/Gibs.cs"
#include "scripts/Q2/Misc.cs"
#include "scripts/Q2/Pickups.cs"
#include "scripts/Q2/Proj.cs"
#include "scripts/Q2/Quad.cs"
#include "scripts/Q2/SpecialMode.cs"

#include "scripts/Weapons/Blaster.cs"
#include "scripts/Weapons/Shotgun.cs"
#include "scripts/Weapons/SuperShotgun.cs"
#include "scripts/Weapons/MachineGun.cs"
#include "scripts/Weapons/Chaingun.cs"
#include "scripts/Weapons/HandGrenade.cs"
#include "scripts/Weapons/GrenadeLauncher.cs"
#include "scripts/Weapons/RocketLauncher.cs"
#include "scripts/Weapons/HyperBlaster.cs"
#include "scripts/Weapons/Railgun.cs"
#include "scripts/Weapons/BFG.cs"

namespace Q2
{

enum eWeapons
{
	Wep_Blaster      = TW_WEAPON_PISTOL,
	Wep_Shotgun      = TW_WEAPON_SHOTGUN,
	Wep_SShotgun     = TW_WEAPON_ASHOTGUN,
	Wep_MachineGun   = TW_WEAPON_RIFLE,
	Wep_Chaingun     = TW_WEAPON_MINIGUN,
	Wep_HandGrenade  = TW_WEAPON_CHRONO,
	Wep_GLauncher    = TW_WEAPON_GRENADE,
	Wep_RLauncher    = TW_WEAPON_MISSILE,
	Wep_HyperBlaster = TW_WEAPON_PULSERIFLE,
	Wep_Railgun      = TW_WEAPON_ACCELERATOR,
	Wep_BFG          = TW_WEAPON_CANNON
}

float WeaponBobAmp = 0;

// initialized/cleared in main.txt, and updated in TurokWeapon::OnTick()
kActor@ WeaponSound;
void PlayWeaponSound( kStr&in sound )
{
	if ( WeaponSound !is null && !WeaponSound.IsStale() ) WeaponSound.PlaySound( sound );
}
void StopWeaponSound()
{
	if ( WeaponSound !is null && !WeaponSound.IsStale() ) WeaponSound.StopSound();
}
void UpdateWeaponSound()
{
	if ( WeaponSound is null ) return;
	if ( !WeaponSound.IsStale() ) WeaponSound.Origin() = Player.Actor().Origin();
	else                          @WeaponSound = null;
}

} // Q2 namespace

//==============================================================================

class TurokWeapon : ScriptObjectWeapon
{
	kWeapon@ self;
	bool bFlash = false;
	int IdleTick = -1;

	TurokWeapon( kWeapon@ actor )
	{
		@self = actor;
	}

	~TurokWeapon()
	{
	}

	//==========================================================================

	void AnimProperties( int&out first, int&out last, bool&out bLoop )
	{
		first = 0; last = 0; bLoop = false;
	}

	void MuzzleFlash()
	{
	}

	//==========================================================================

	kPuppet@ OwnerP()
	{
		return self.Owner().Actor();
	}
	kActor@ OwnerA()
	{
		return self.Owner().Actor().CastToActor();
	}

	bool FirePressed()
	{
		return self.Owner().Buttons() & BC_ATTACK != 0;
	}

	bool OwnerDying()
	{
		// dead or falling
		return OwnerP().Flags() & AF_DEAD != 0 || OwnerP().PlayerFlags() & (1<<12) != 0;
	}

	int GetAmmo()
	{
		return self.Owner().GetAmmo( self.Owner().CurrentWeapon() );
	}
	bool HasAmmo( int amt=1, bool bSwitch=false )
	{
		if ( GetAmmo() >= amt )
			return true;
		if ( bSwitch )
			ForceSwitch();
		return false;
	}
	bool UseAmmo( int amt )
	{
		if ( !HasAmmo( amt, true ) )
			return false;
		self.Owner().ConsumeAmmo( amt );
		// normally when ammo reaches 0, weapon switches automatically
		// so trigger a switch if ammo drops below min to fire
		HasAmmo( amt, true );
		return true;
	}
	void ForceSwitch()
	{
		int ammo = GetAmmo();
		if ( ammo > 0 )
		{
			// use up ammo to trigger weapon change
			self.Owner().ConsumeAmmo( ammo );
			// then give it right back (unless infinite ammo is on and we took none)
			if ( GetAmmo() < ammo )
				self.Owner().GiveWeapon( self.Owner().CurrentWeapon(), ammo );
		}
	}

	kVec3 FOVOffset( const array<kVec3>&in offsets )
	{
		float FOV = 74;
		kStr str;
		if ( Sys.GetCvarValue( "r_fov", str ) )
			FOV = str.Atof();
		if      ( FOV <=  74 ) return offsets[0].Lerp( offsets[1], (FOV- 47.5f)/( 74.0f- 47.5f) );
		else if ( FOV <=  90 ) return offsets[1].Lerp( offsets[2], (FOV- 74.0f)/( 90.0f- 74.0f) );
		else if ( FOV <= 110 ) return offsets[2].Lerp( offsets[3], (FOV- 90.0f)/(110.0f- 90.0f) );
		else    /*FOV >  110*/ return offsets[3].Lerp( offsets[4], (FOV-110.0f)/(120.0f-110.0f) );
	}
	float FOVOffset( const array<float>&in offsets )
	{
		float FOV = 74;
		kStr str;
		if ( Sys.GetCvarValue( "r_fov", str ) )
			FOV = str.Atof();
		if      ( FOV <=  74 ) return Math::Lerp( offsets[0], offsets[1], (FOV- 47.5f)/( 74.0f- 47.5f) );
		else if ( FOV <=  90 ) return Math::Lerp( offsets[1], offsets[2], (FOV- 74.0f)/( 90.0f- 74.0f) );
		else if ( FOV <= 110 ) return Math::Lerp( offsets[2], offsets[3], (FOV- 90.0f)/(110.0f- 90.0f) );
		else    /*FOV >  110*/ return Math::Lerp( offsets[3], offsets[4], (FOV-110.0f)/(120.0f-110.0f) );
	}

	// check position from eye, rather than from foot
	kVec3 CheckPosition( kVec3 v )
	{
		float r = OwnerP().Radius();
		float h = OwnerP().Height();
		OwnerP().Radius() = OwnerP().Height() = 0;
		kVec3 origin = OwnerP().Origin();
		OwnerP().Origin().z = v.z;
		if ( !OwnerP().CheckPosition(v) )
			v = CModel.InterceptVector();
		OwnerP().Origin() = origin;
		OwnerP().Radius() = r;
		OwnerP().Height() = h;
		return v;
	}

	void SpawnProj( const kStr&in type, kVec3&in offset, const kQuat&in q )
	{
		kVec3 v = CheckPosition( Q2::EyePos() + offset * OwnerP().Rotation() );
		Game.SpawnFx( type, OwnerP(), v, q );
	}
	void SpawnProj( const kStr&in type, kVec3&in offset, const kVec3&in dir )
	{
		SpawnProj( type, offset, dir.ToQuat() );
	}

	int PlayingID()
	{
		return self.AnimState().PlayingID();
	}
	bool IsPlaying( int animID )
	{
		return self.AnimState().IsPlaying( animID );
	}
	float PlayTime()
	{
		return self.AnimState().PlayTime();
	}

	void Animate()
	{
		self.AnimState().flags |= ANF_LOOP;
		self.AnimState().flags &= ~ANF_CYCLECOMPLETED;
		int first, last, v;
		bool bLoop;

		AnimProperties( first, last, bLoop );

		switch ( PlayingID() )
		{
			// prevent idle anim from restarting when moving/stopping with generic weapon bob turned off
			case anim_weaponWalk: case anim_weaponRun: case anim_weaponIdle:
				if ( IdleTick == -1 ) IdleTick = self.GameTicks();
				v = first + self.GameTicks() - IdleTick;
				break;
			default:
				IdleTick = -1;
				v = first + int( PlayTime() * 60 + 0.5f );
		}
		if ( bLoop )
			v = first + ( (v-first) % (last-first+1) );
		else if ( v >= last )
		{
			v = last;
			AnimEnd();
		}
		self.ModelVariation() = v;
		RunAnim();
	}
	void AnimEnd()
	{
//		self.AnimState().flags |= ANF_CYCLECOMPLETED | ANF_STOPPED;
		self.AnimState().flags = ANF_STOPPED | ANF_CYCLECOMPLETED;
	}

	float FakeRoot( float f, float r )
	{
		f -= 1;
		return 1 - Math::Pow( -f, r );
	}
	void RunAnim()
	{
		kStr generic;
		if ( Sys.GetCvarValue( "g_weaponbobbing", generic ) && generic.Atoi() == 1 )
		{
			self.RenderModel().Offset() = Math::vecZero;
			self.RenderModel().SetRotationOffset( 0, 0, 0,0,1 );
			return;
		}
		float t = self.GameTicks() / 9.0f;
		float amp = 0;
		if ( OwnerP().OnGround() && !OwnerP().InWater() )
		{
			amp = ( OwnerP().Movement() * kVec3(1,1,0) ).Unit();
			float max, fric;
			OwnerP().Definition().GetFloat( "player.groundForwardSpeed", max, 12.8f );
			OwnerP().Definition().GetFloat( "friction", fric, 0.5f );
			max *= fric;
			if ( amp > max ) amp = max;
		}
		Q2::WeaponBobAmp = Math::Lerp( Q2::WeaponBobAmp, amp, 0.1f );
//		self.RenderModel().Offset().x = -( self.RenderModel().Offset().y = amp * Math::Sin(t) );
//		self.RenderModel().Offset().z = amp/2 * Math::Cos(2*t);
		amp = Q2::WeaponBobAmp * 1.25f;
		self.RenderModel().SetRotationOffset( 0, amp/200 * Math::Sin( t ), 0,1,1 );
		self.RenderModel().Offset().z = amp/3 * Math::Cos(2*t);
/*		float f = Math::Sin( t );
		f = FakeRoot( Math::Fabs(f), 1.25f ) * (f > 0 ? 1.0f : -1.0f);
		self.RenderModel().SetRotationOffset( 0, amp/200.0f * f, 0,1,1 );
		f = Math::Cos( 2*t );
		f = FakeRoot( Math::Fabs(f), 1.25f ) * (f > 0 ? 1.0f : -1.0f);
		self.RenderModel().Offset().z = amp/3.0f * f;
*/	}

	void OnTick()
	{
		// prevent being given 3 grenades with "chronoscepter" message
		// if you collect all 8 chrono piece stand-ins without T+ installed
		GameVariables.SetValue( "chronoPieceFlags", "0" );
		Animate();
		Q2::QuadTick( self );
		Q2::UpdateWeaponSound();
		if ( bFlash )
		{
			MuzzleFlash();
			bFlash = false;
		}
	}

	void OnActorTick()
	{
		if ( PlayingID() != anim_weaponSwapOut || !self.AnimState().Stopped() )
			OnTick();
	}

	void OnBeginFire() {}
	void OnFire() {}
	void OnEndFire() {}

	void OnRaise() {}
	void OnLower() {}
	void OnHoldster() {}
}

namespace Q2
{

final class WeaponStub : TurokWeapon
{
	WeaponStub( kWeapon@ A ) { super(A); }
	void OnTick() { self.Owner().RemoveWeapon( self.Owner().CurrentWeapon() ); }
	void OnBeginFire() { self.PreventFire() = true; }
}

}
