/* 
* The Opposing Force version of the m249
*/

namespace OF_M249
{

enum m249_e
{
	M249_SLOWIDLE = 0,
	M249_IDLE2,
	M249_RELOAD_START,
	M249_RELOAD_END,
	M249_HOLSTER,
	M249_DRAW,
	M249_SHOOT1,
	M249_SHOOT2,
	M249_SHOOT3,
};

// Models
string W_MODEL		= "models/txas/wpn/w_smartgun.mdl";
string V_MODEL		= "models/txas/wpn/v_saw_smartgun.mdl";
string P_MODEL		= "models/txas/wpn/p_smartgun.mdl";
string A_MODEL		= "models/txas/item/w_saw_clip.mdl";
string S_MODEL		= "models/txas/wpn/shell_null.mdl"; // Change this manually in MapInit function, ex: OF_M249::S_MODEL = "models/mymodel.mdl";
// Sprites
string SPR_DIR		= "txas/wpn/";
// Sounds
array<string> Sounds = { 
		"txas/wpn/smart_fire1.ogg",
		"txas/wpn/smart_fire2.ogg",
		"txas/wpn/smart_fire3.ogg",
		"weapons/saw_coveropen.wav",
		"weapons/saw_boxout.wav",
		"weapons/saw_boxin.wav",
		"weapons/saw_beltin.wav",
		"weapons/saw_coverdown.wav",
		"weapons/saw_bolt.wav",
		"hlclassic/weapons/357_cock1.wav"
};
string AMMO_PICKUP	= "hlclassic/items/9mmclip1.wav";
// Weapon information
int MAX_CARRY		= 800; //200; Swap values if you want the default OF values
int MAX_CLIP		= 200; //50; Swap values if you want the default OF values
int DEFAULT_GIVE	= 200;
int WEIGHT		= 20;
int FLAGS		= 0;
uint SLOT		= 5;
uint POSITION		= 6;
string AMMO_TYPE 	= "556";

// Smartgun tuning
float SMART_CONE_DEG	= 35.0;	// Lock-on cone around the crosshair, in degrees. With the default 90 degree FOV the screen edge is 45 degrees away horizontally
float SMART_RANGE		= 4096.0;	// How far away targets can be locked (units)
int SMART_MAX_TRACES	= 4;	// Max line traces per target search (the search runs 10 times a second, not per shot)
Vector SMART_SPREAD		= VECTOR_CONE_4DEGREES;	// Bullet spread. Smaller = tighter (1 degree is nearly a laser, the old M249 used 2 to 6)
float SMART_RECOIL		= 0.3;	// Max view punch per shot (the original M249 used 2.0 / 1.0)

// Where on a target to aim: heights (0 = bottom of its box, 1 = top), best first. Each one costs at most one trace,
// and the first ray that really lands on the target's hitboxes decides the aim spot.
array<float> SMART_AIM_HEIGHTS	= { 0.65, 0.40 };
int SMART_ARMOR_HITGROUP	= 10;	// Armored hitbox group: only used if no other hitbox can be hit

// Smartgun aim marker (placeholder sprite borrowed from the Failnaught script)
string SMART_MARK_SPRITE	= "sprites/svencontra2/aim_sprite.spr";
float SMART_MARK_RATE		= 0.1;	// Seconds between marker updates. Should match the sprite's lifetime (see notes) so only ONE is on screen
int SMART_MARK_SCALE_MIN	= 3;	// Marker size limits (value * 10 = scale, like TE_SPRITE expects)
int SMART_MARK_SCALE_MAX	= 25;
int SMART_MARK_BRIGHTNESS	= 200;
float SMART_MARK_OFFSET	= 6.0;	// How far in front of the hit surface the marker floats (so the model doesn't hide it)
int iSmartMarkSprite		= 0;	// Filled in by Precache

// Per-player lock-on state. The marker (10 times a second) finds the target and stores it here,
// and every shot just reads it, so firing costs almost nothing.
array<EHandle> g_hSmartTarget( 33 );
array<Vector> g_vecSmartOffset( 33 );	// Aim spot relative to the target's origin, so it follows the target as it moves
array<bool> g_bSmartLock( 33, true );	// Secondary fire switches this. Off = no search, no marker, bullets go straight
int g_iSmartTraces = 0;

// Reload timing: each value must be the EXACT length of that viewmodel sequence in seconds (frames / fps).
// The original M249 used roughly 1.5 (start) and 2.28 (end), for a 3.78s total.
float RELOAD_START_TIME	= 2.36;	// Length of the M249_RELOAD_START sequence
float RELOAD_END_TIME		= 1.80;	// Length of the M249_RELOAD_END sequence

void ClearSmartTarget( int iPlayerIndex )
{
	if( iPlayerIndex > 0 && iPlayerIndex < int( g_hSmartTarget.length() ) )
		g_hSmartTarget[iPlayerIndex] = null;
}

// Finds a spot on one target that really is on its hitboxes, with at most a couple of rays.
bool FindAimPoint( CBasePlayer@ pPlayer, CBaseEntity@ pTarget, const Vector& in vecSrc, Vector& out vecHit )
{
	Vector vecMin = pTarget.pev.absmin;
	Vector vecMax = pTarget.pev.absmax;
	Vector vecCenter = ( vecMin + vecMax ) * 0.5;

	const float flHeight = vecMax.z - vecMin.z;
	const float flReach = ( vecMax - vecMin ).Length();	// Rays go this far past the sample point, to land on the model behind it

	bool bHaveArmorHit = false;
	Vector vecArmorHit;

	for( uint h = 0; h < SMART_AIM_HEIGHTS.length() && g_iSmartTraces < SMART_MAX_TRACES; ++h )
	{
		Vector vecSample = vecCenter;
		vecSample.z = vecMin.z + SMART_AIM_HEIGHTS[h] * flHeight;

		Vector vecDir = ( vecSample - vecSrc ).Normalize();

		TraceResult tr;
		++g_iSmartTraces;
		g_Utility.TraceLine( vecSrc, vecSample + vecDir * flReach, dont_ignore_monsters, pPlayer.edict(), tr );

		// Must hit this target itself: a wall, another monster or empty space means this ray is no good
		if( tr.flFraction >= 1.0 || tr.pHit is null || g_EntityFuncs.Instance( tr.pHit ) !is pTarget )
			continue;

		if( tr.iHitgroup == SMART_ARMOR_HITGROUP )
		{
			if( !bHaveArmorHit )
			{
				vecArmorHit = tr.vecEndPos;
				bHaveArmorHit = true;
			}
			continue;
		}

		vecHit = tr.vecEndPos;
		return true;
	}

	if( bHaveArmorHit )
	{
		vecHit = vecArmorHit;
		return true;
	}

	return false;
}

// Smartgun targeting: the hostile closest to the crosshair, inside the lock-on cone and visible.
// vecAimPoint receives the spot on its hitboxes to shoot at. Only the marker calls this (10 times a second).
CBaseEntity@ FindSmartTarget( CBasePlayer@ pPlayer, const Vector& in vecSrc, Vector& out vecAimPoint )
{
	Vector vecForward, vecRight, vecUp;
	g_EngineFuncs.AngleVectors( pPlayer.pev.v_angle + pPlayer.pev.punchangle, vecForward, vecRight, vecUp );

	vecAimPoint = vecSrc + vecForward * 8192.0;
	g_iSmartTraces = 0;

	CBaseEntity@ pBest = null;
	float flBestDot = cos( SMART_CONE_DEG * Math.PI / 180.0 );

	CBaseEntity@ pEnt = null;
	while( ( @pEnt = g_EntityFuncs.FindEntityInSphere( pEnt, vecSrc, SMART_RANGE, "*", "classname" ) ) !is null )
	{
		if( g_iSmartTraces >= SMART_MAX_TRACES )
			break;

		if( pEnt is pPlayer || !pEnt.IsAlive() || pEnt.pev.takedamage == DAMAGE_NO )
			continue;

		if( !pEnt.IsMonster() && !pEnt.IsPlayer() )
			continue;

		// Only lock onto things that are hostile to the player (skips allies / friendly NPCs / teammates)
		if( pPlayer.IRelationship( pEnt ) < R_DL )
			continue;

		// Free pre-check on the middle of its box: skip anything that can't beat the current best
		if( DotProduct( vecForward, ( pEnt.Center() - vecSrc ).Normalize() ) <= flBestDot )
			continue;

		// The only expensive step, and only for targets that are actually better than what we have
		Vector vecPoint;
		if( !FindAimPoint( pPlayer, pEnt, vecSrc, vecPoint ) )
			continue;

		float flDot = DotProduct( vecForward, ( vecPoint - vecSrc ).Normalize() );
		if( flDot <= flBestDot )
			continue;

		flBestDot = flDot;
		@pBest = pEnt;
		vecAimPoint = vecPoint;
	}

	return pBest;
}

class weapon_ofm249 : ScriptBasePlayerWeaponEntity
{
	private CBasePlayer@ m_pPlayer
	{
		get const	{ return cast<CBasePlayer@>( self.m_hPlayer.GetEntity() ); }
		set		{ self.m_hPlayer = EHandle( @value ); }
	}
	private int m_iShell;
	private int GetBodygroup()
	{
		if( self.m_iClip == 0 )
			return 8;
		else if( self.m_iClip <= 7 )
			return 9 - self.m_iClip;
		else
			return 0;
	}

	float WeaponTimeBase()
	{
		return g_Engine.time;
	}

	void GetDefaultShellInfo( CBasePlayer@ pPlayer, Vector& out ShellVelocity, Vector& out ShellOrigin, float forwardScale, float upScale, float rightScale )
	{
		Vector vecForward, vecRight, vecUp;

		g_EngineFuncs.AngleVectors( pPlayer.pev.v_angle, vecForward, vecRight, vecUp );

		const float fR = Math.RandomFloat( 50.0, 70.0 );
		const float fU = Math.RandomFloat( 100.0, 150.0 );

		for( int i = 0; i < 3; ++i )
		{
			ShellVelocity[i] = pPlayer.pev.velocity[i] + vecRight[i] * fR + vecUp[i] * fU + vecForward[i] * 25;
			ShellOrigin[i]   = pPlayer.pev.origin[i] + pPlayer.pev.view_ofs[i] + vecUp[i] * upScale + vecForward[i] * forwardScale + vecRight[i] * rightScale;
		}
	}

	// Direction the bullets should travel: towards the target the marker has locked, or straight ahead.
	// No searching or tracing here, it only reads what the marker found.
	Vector GetSmartAimVector( const Vector& in vecSrc )
	{
		Vector vecForward, vecRight, vecUp;
		g_EngineFuncs.AngleVectors( m_pPlayer.pev.v_angle + m_pPlayer.pev.punchangle, vecForward, vecRight, vecUp );

		const int iIndex = m_pPlayer.entindex();
		CBaseEntity@ pTarget = g_hSmartTarget[iIndex].GetEntity();

		if( pTarget is null || !pTarget.IsAlive() )
			return vecForward;

		Vector vecDir = ( pTarget.pev.origin + g_vecSmartOffset[iIndex] - vecSrc ).Normalize();

		// The lock is up to 0.1s old: ignore it if the player has already turned well away from it
		if( DotProduct( vecForward, vecDir ) < cos( SMART_CONE_DEG * 1.2 * Math.PI / 180.0 ) )
			return vecForward;

		return vecDir;
	}

	private EHandle m_hMarker;

	void CreateMarker()
	{
		RemoveMarker();

		CBaseEntity@ pMarker = g_EntityFuncs.Create( "smartgun_marker", m_pPlayer.pev.origin, g_vecZero, false, m_pPlayer.edict() );
		if( pMarker !is null )
			m_hMarker = EHandle( pMarker );
	}

	void RemoveMarker()
	{
		CBasePlayer@ pPlayer = m_pPlayer;
		if( pPlayer !is null )
			ClearSmartTarget( pPlayer.entindex() );

		if( m_hMarker.IsValid() )
			g_EntityFuncs.Remove( m_hMarker.GetEntity() );

		m_hMarker = null;
	}

	void Spawn()
	{
		Precache();
		g_EntityFuncs.SetModel( self, self.GetW_Model( W_MODEL ) );
		self.m_iDefaultAmmo = DEFAULT_GIVE;
		self.FallInit();
	}

	void Precache()
	{	
		self.PrecacheCustomModels();
		g_Game.PrecacheModel( "models/txas/wpn/v_saw_smartgun.mdl" );
		g_Game.PrecacheModel( "models/txas/wpn/w_smartgun.mdl" );
		g_Game.PrecacheModel( "models/txas/wpn/p_smartgun.mdl" );
		g_Game.PrecacheModel( "models/txas/item/w_saw_clip.mdl" );
		
		m_iShell = g_Game.PrecacheModel( "models/txas/wpn/shell_null.mdl" );
		
		iSmartMarkSprite = g_Game.PrecacheModel( "sprites/svencontra2/aim_sprite.spr" );

		g_Game.PrecacheOther( GetAmmoName() );

		/*
		for( uint i = 0; i < Sounds.length(); i++ )
		{
			g_SoundSystem.PrecacheSound( Sounds[i] );
			g_Game.PrecacheGeneric( "sound/" + Sounds[i] );
		}
		*/
		
		g_SoundSystem.PrecacheSound( "txas/wpn/smart_fire1.ogg" );
		g_SoundSystem.PrecacheSound( "txas/wpn/smart_fire2.ogg" );
		g_SoundSystem.PrecacheSound( "txas/wpn/smart_fire3.ogg" );
		g_SoundSystem.PrecacheSound( "weapons/saw_coveropen.wav" );
		g_SoundSystem.PrecacheSound( "weapons/saw_boxout.wav" );
		g_SoundSystem.PrecacheSound( "weapons/saw_boxin.wav" );
		g_SoundSystem.PrecacheSound( "weapons/saw_beltin.wav" );
		g_SoundSystem.PrecacheSound( "weapons/saw_coverdown.wav" );
		g_SoundSystem.PrecacheSound( "hlclassic/weapons/357_cock1.wav" );
		g_SoundSystem.PrecacheSound( "hlclassic/items/9mmclip1.wav" );
		
		g_Game.PrecacheGeneric( "sprites/txas/wpn/weapon_ofm249.txt" );
	}

	bool GetItemInfo( ItemInfo& out info )
	{
		info.iMaxAmmo1	= MAX_CARRY;
		info.iAmmo1Drop	= MAX_CLIP;
		info.iMaxAmmo2	= -1;
		info.iAmmo2Drop	= -1;
		info.iMaxClip	= MAX_CLIP;
		info.iSlot	= SLOT;
		info.iPosition	= POSITION;
		info.iId	= g_ItemRegistry.GetIdForName( self.pev.classname );
		info.iFlags	= FLAGS;
		info.iWeight	= WEIGHT;

		return true;
	}

	bool AddToPlayer( CBasePlayer@ pPlayer )
	{
		if( !BaseClass.AddToPlayer( pPlayer ) )
			return false;

		NetworkMessage message( MSG_ONE, NetworkMessages::WeapPickup, pPlayer.edict() );
			message.WriteLong( g_ItemRegistry.GetIdForName( self.pev.classname ) );
		message.End();

		return true;
	}

	bool Deploy()
	{
		bool bResult = self.DefaultDeploy( self.GetV_Model( V_MODEL ), self.GetP_Model( P_MODEL ), M249_DRAW, "egon", 0, GetBodygroup() );
		self.m_flTimeWeaponIdle = WeaponTimeBase() + 1.0;
		CreateMarker();
		return bResult;
	}

	bool PlayEmptySound()
	{
		if( self.m_bPlayEmptySound )
		{
			self.m_bPlayEmptySound = false;
			g_SoundSystem.EmitSoundDyn( m_pPlayer.edict(), CHAN_WEAPON, Sounds[9], 0.8, ATTN_NORM, 0, PITCH_NORM );
		}

		return false;
	}

	void Holster( int skiplocal = 0 )
	{
		self.m_fInReload = false;
		SetThink( null );
		RemoveMarker();

		BaseClass.Holster( skiplocal );
	}

	void PrimaryAttack()
	{
		if( self.m_iClip <= 0 || m_pPlayer.pev.waterlevel == WATERLEVEL_HEAD )
		{
			self.PlayEmptySound();
			self.m_flNextPrimaryAttack = WeaponTimeBase() + 0.15;
			return;
		}

		--self.m_iClip;
		// Fill g_Engine.v_forward/v_right/v_up for THIS player (they are shared globals)
		Math.MakeVectors( m_pPlayer.pev.v_angle + m_pPlayer.pev.punchangle );
		
		Vector vecSrc	 = m_pPlayer.GetGunPosition();
		// Smartgun: auto-track the nearest hostile in the lock-on cone, and fire with (near) zero spread
		Vector vecAiming = GetSmartAimVector( vecSrc );
		Vector vecSpread = SMART_SPREAD;

		m_pPlayer.FireBullets( 1, vecSrc, vecAiming, vecSpread, 8192, BULLET_PLAYER_SAW, 2 );
		g_SoundSystem.EmitSoundDyn( m_pPlayer.edict(), CHAN_WEAPON, Sounds[Math.RandomLong(0,2)], VOL_NORM, ATTN_NORM, 0, 94 + Math.RandomLong(0,15) );

		Vector vecShellVelocity, vecShellOrigin;
		GetDefaultShellInfo( m_pPlayer, vecShellVelocity, vecShellOrigin, 24.0, -28.0, 4.0 );
		g_EntityFuncs.EjectBrass( vecShellOrigin, vecShellVelocity, m_pPlayer.pev.angles.y, m_iShell, TE_BOUNCE_SHELL );

		if( self.m_iClip <= 0 && m_pPlayer.m_rgAmmo( self.m_iPrimaryAmmoType ) <= 0 )
			m_pPlayer.SetSuitUpdate( "!HEV_AMO0", false, 0 );

		m_pPlayer.pev.effects |= EF_MUZZLEFLASH;
		self.pev.effects |= EF_MUZZLEFLASH;

		m_pPlayer.SetAnimation( PLAYER_ATTACK1 );
		self.SendWeaponAnim( m249_e(Math.RandomLong(6,8)), 0, GetBodygroup() );

		m_pPlayer.m_iWeaponVolume = NORMAL_GUN_VOLUME;
		m_pPlayer.m_iWeaponFlash = NORMAL_GUN_FLASH;

		m_pPlayer.pev.punchangle.x = Math.RandomFloat( -SMART_RECOIL, SMART_RECOIL );
		m_pPlayer.pev.punchangle.y = Math.RandomFloat( -SMART_RECOIL * 0.5, SMART_RECOIL * 0.5 );

		self.m_flNextPrimaryAttack = WeaponTimeBase() + 0.05;
		self.m_flTimeWeaponIdle = WeaponTimeBase() + 0.2;

		const Vector vecVelocity = m_pPlayer.pev.velocity;
		const float flZVel = m_pPlayer.pev.velocity.z;
		Vector vecInvPushDir = g_Engine.v_forward * 35.0;
		float flNewZVel = g_EngineFuncs.CVarGetFloat( "sv_maxspeed" );

		if( vecInvPushDir.z >= 10.0 )
			flNewZVel = vecInvPushDir.z;

		if( !IsMultiplayer )
		{
			m_pPlayer.pev.velocity = m_pPlayer.pev.velocity - vecInvPushDir;
			m_pPlayer.pev.velocity.z = flZVel;
		}
		else
		{
			const float flZTreshold = -( flNewZVel + 100.0 );

			if( vecVelocity.x > flZTreshold )
				m_pPlayer.pev.velocity.x -= vecInvPushDir.x;

			if( vecVelocity.y > flZTreshold )
				m_pPlayer.pev.velocity.y -= vecInvPushDir.y;

			m_pPlayer.pev.velocity.z -= vecInvPushDir.z;
		}
		
		/*
		TraceResult tr;
		float x, y;

		g_Utility.GetCircularGaussianSpread( x, y );

		Vector vecDir = vecAiming + x * vecSpread.x * g_Engine.v_right + y * vecSpread.y * g_Engine.v_up;
		Vector vecEnd = vecSrc + vecDir * 8192;

		g_Utility.TraceLine( vecSrc, vecEnd, dont_ignore_monsters, m_pPlayer.edict(), tr );

		if( tr.flFraction < 1.0 )
		{
			if( tr.pHit !is null )
			{
				CBaseEntity@ pHit = g_EntityFuncs.Instance( tr.pHit );

				g_SoundSystem.PlayHitSound( tr, vecSrc, vecEnd, BULLET_PLAYER_SAW );
				g_Utility.BubbleTrail( vecSrc, tr.vecEndPos, int((8192 * tr.flFraction)/64.0) );

				if( pHit is null || pHit.IsBSPModel() )
					g_WeaponFuncs.DecalGunshot( tr, BULLET_PLAYER_SAW );
			}
		}
		*/
	}

	// Secondary fire: switch the lock-on on or off
	void SecondaryAttack()
	{
		const int iIndex = m_pPlayer.entindex();

		g_bSmartLock[iIndex] = !g_bSmartLock[iIndex];

		// Drop any current lock right away so the very next shot already fires straight
		if( !g_bSmartLock[iIndex] )
			ClearSmartTarget( iIndex );

		g_SoundSystem.EmitSoundDyn( m_pPlayer.edict(), CHAN_ITEM, Sounds[9], 0.6, ATTN_NORM, 0, g_bSmartLock[iIndex] ? 115 : 85 );
		g_PlayerFuncs.ClientPrint( m_pPlayer, HUD_PRINTCENTER, g_bSmartLock[iIndex] ? "Smart lock: ON\n" : "Smart lock: OFF\n" );

		self.m_flNextSecondaryAttack = WeaponTimeBase() + 0.5;
	}

	void FinishAnim()
	{
		if( !self.m_fInReload )
			return;

		// Body 0: the new belt is loaded by the time this animation plays
		self.SendWeaponAnim( M249_RELOAD_END, 0, 0 );
		SetThink( null );
	}

	void Reload()
	{
		if( self.m_iClip == MAX_CLIP || m_pPlayer.m_rgAmmo( self.m_iPrimaryAmmoType ) <= 0 )
			return;

		const float flTotalTime = RELOAD_START_TIME + RELOAD_END_TIME;

		// Ammo is refilled and firing is blocked until BOTH sequences are done
		if( !self.DefaultReload( MAX_CLIP, M249_RELOAD_START, flTotalTime, GetBodygroup() ) )
			return;

		// The second sequence starts the moment the first one ends
		SetThink( ThinkFunction( this.FinishAnim ) );
		self.pev.nextthink = WeaponTimeBase() + RELOAD_START_TIME;

		self.m_flNextPrimaryAttack = WeaponTimeBase() + flTotalTime;
		self.m_flTimeWeaponIdle    = WeaponTimeBase() + flTotalTime;

		m_pPlayer.SetAnimation( PLAYER_RELOAD );
		m_pPlayer.pev.framerate = 1.00;
	}

	void WeaponIdle()
	{
		self.ResetEmptySound();

		if( self.m_flTimeWeaponIdle > WeaponTimeBase() )
			return;

		float flRand = g_PlayerFuncs.SharedRandomFloat( m_pPlayer.random_seed, 0.0, 1.0 );
		if( flRand <= 0.95 )
		{
			self.SendWeaponAnim( M249_SLOWIDLE, 0, GetBodygroup() );
			self.m_flTimeWeaponIdle = WeaponTimeBase() + 1.0;
		}
		else
		{
			self.SendWeaponAnim( M249_IDLE2, 0, GetBodygroup() );
			self.m_flTimeWeaponIdle = WeaponTimeBase() + 6.67;	
		}
	}
}

// Draws the single aim-assist marker. It's a separate entity (like fn_stackent in the Failnaught script)
// so it has its own think and doesn't fight with the weapon's reload think.
class smartgun_marker : ScriptBaseEntity
{
	void Spawn()
	{
		pev.movetype = MOVETYPE_NONE;
		pev.solid = SOLID_NOT;

		SetThink( ThinkFunction( this.MarkerThink ) );
		pev.nextthink = g_Engine.time + SMART_MARK_RATE;
	}

	void MarkerThink()
	{
		CBasePlayer@ pPlayer = cast<CBasePlayer@>( g_EntityFuncs.Instance( pev.owner ) );

		if( pPlayer is null || !pPlayer.IsConnected() || !pPlayer.IsAlive() )
		{
			ClearSmartTarget( g_EntityFuncs.EntIndex( pev.owner ) );
			g_EntityFuncs.Remove( self );
			return;
		}

		// Only show while the smartgun is the weapon in hand
		CBaseEntity@ pActive = pPlayer.m_hActiveItem.GetEntity();
		if( pActive is null || pActive.GetClassname() != GetName() )
		{
			ClearSmartTarget( pPlayer.entindex() );
			g_EntityFuncs.Remove( self );
			return;
		}

		const int iIndex = pPlayer.entindex();

		// Lock switched off (secondary fire): no search, no sprite
		if( !g_bSmartLock[iIndex] )
		{
			ClearSmartTarget( iIndex );
			pev.nextthink = g_Engine.time + SMART_MARK_RATE;
			return;
		}

		Vector vecSrc = pPlayer.GetGunPosition();
		Vector vecAimPoint;
		CBaseEntity@ pTarget = FindSmartTarget( pPlayer, vecSrc, vecAimPoint );

		// No hostile target in the cone: no marker, and the gun just fires straight
		if( pTarget is null )
		{
			ClearSmartTarget( iIndex );
			pev.nextthink = g_Engine.time + SMART_MARK_RATE;
			return;
		}

		// Hand the lock to the weapon (stored relative to the target so it keeps up with it)
		g_hSmartTarget[iIndex] = EHandle( pTarget );
		g_vecSmartOffset[iIndex] = vecAimPoint - pTarget.pev.origin;

		// Float just in front of the aim spot: a sprite inside the model would be hidden by it
		Vector vecPos = vecAimPoint - ( vecAimPoint - vecSrc ).Normalize() * SMART_MARK_OFFSET;

		// Scale with the enemy's height (5 = 0.5x for a ~72 unit tall zombie, same idea as the Failnaught marks)
		int iScale = Math.clamp( SMART_MARK_SCALE_MIN, SMART_MARK_SCALE_MAX, int( 5.0 * pTarget.pev.size.z / 72.0 ) );

		// Sent to the owner only, so teammates don't see it
		NetworkMessage m( MSG_ONE, NetworkMessages::SVC_TEMPENTITY, pPlayer.edict() );
			m.WriteByte( TE_SPRITE );
			m.WriteCoord( vecPos.x );
			m.WriteCoord( vecPos.y );
			m.WriteCoord( vecPos.z );
			m.WriteShort( iSmartMarkSprite );
			m.WriteByte( iScale );	// scale * 10
			m.WriteByte( SMART_MARK_BRIGHTNESS );
		m.End();

		pev.nextthink = g_Engine.time + SMART_MARK_RATE;
	}
}

/*
class ammo_of556 : ScriptBasePlayerAmmoEntity
{
	void Spawn()
	{
		Precache();
		g_EntityFuncs.SetModel( self, A_MODEL );
		BaseClass.Spawn();
	}

	void Precache()
	{
		g_Game.PrecacheModel( A_MODEL );
		g_SoundSystem.PrecacheSound( AMMO_PICKUP );
	}

	bool AddAmmo( CBaseEntity@ pOther )
	{
		if( pOther.GiveAmmo( MAX_CLIP, AMMO_TYPE, MAX_CARRY ) != -1 )
		{
			g_SoundSystem.EmitSoundDyn( self.edict(), CHAN_ITEM, AMMO_PICKUP, VOL_NORM, ATTN_NORM, 0, PITCH_NORM );
			return true;
		}
		return false;
	}
}
*/

string GetAmmoName()
{
	return "ammo_556";
} 

string GetName()
{
	return "weapon_ofm249";
}

void Register()
{
	
	//if( !g_CustomEntityFuncs.IsCustomEntity( GetAmmoName() ) )
	//	g_CustomEntityFuncs.RegisterCustomEntity( "OF_M249::ammo_of556", GetAmmoName() );
	
	
	if( !g_CustomEntityFuncs.IsCustomEntity( "smartgun_marker" ) )
		g_CustomEntityFuncs.RegisterCustomEntity( "OF_M249::smartgun_marker", "smartgun_marker" );

	if( !g_CustomEntityFuncs.IsCustomEntity( GetName() ) )
	{
		g_CustomEntityFuncs.RegisterCustomEntity( "OF_M249::weapon_ofm249", GetName() );
		g_ItemRegistry.RegisterWeapon( GetName(), SPR_DIR, AMMO_TYPE, "", GetAmmoName() );
	}
}

}

