//
// 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:
//      Enemy/Monster Script Object Classes
//

#include "scripts/common.txt"

//-----------------------------------------------------------------------------
//
// Enemy Base Class
//
//-----------------------------------------------------------------------------

/*
==============================================================
TurokEnemy
==============================================================
*/

// Smoke39 - delayed damage types:
// BonusDamage - dealt in bulk next frame (game will scale it by difficulty)
// burnAccumulator - dealt one point at a time to avoid difficulty scale rounding errors (use IncBurnAccumulator() to pre-scale)

bool bApplyingBonusDamage = false; // bonus damage is being applied - do not re-apply bonuses to it

class TurokEnemy : ScriptObject
{
	kActor @self;
	bool m_bMortallyWounded;
	bool m_bDroppedItem;
	kAngle m_lookAngle;
	float m_deathFreezeTime;
	// Smoke39
	bool bNuke = false; // m_deathFreezeTime is counting down nuke death, not shockwave
	array<float> AlienFreezeTimes;
	array<kVec3> AlienFreezeLocs;
	float InitialHeight;
	float oldRadius, oldHeight;
//	bool bWasInWater = true;
	bool bDeathTaunt = false;
	kDictMem@ DeathDamDef;
	kActor@ oldTarget;
	float PlayerVisibleTime = 0; // time with LOS between self and player
//	float PlayerSightedTime = 0; // time actually looking at player
	int LastAgitatedTick = int( -12 / GAME_DELTA_TIME );
	int BonusDamage; // additional damage, waiting to be applied a frame later, outside of OnDamge()
	int LastScaledTick = -1;
	// fire stuff
	int flameTick = 0;                 // tick we last took fire damage on
	float burnFactor = 0;              // how "on fire" we are (0 to 1)
	float burnAccumulator = 0;         // take damage every time this counts up to 1
	float burnParticleAccumulator = 0; // spawn a flame particle every time this counts up to 1
	float burnSmokeFactor = 0;
	float burnSmokeAccumulator = 0;
	float burnSteamAccumulator = 0;
	// charge dart stun
	float StunTime = 0, StunOverflow = 0;
	float StunYaw;
	float StunParticleAccumulator = 0, StunSmokeAccumulator = 0;
	bool bStunTeleportHack = false;
	// sunfire pod daze
	float DazeTime = 0;
	// tranq / poison dart stuff
	float Sedation = 0, SedationOverflow = 0;
	bool bSedated = false; // enemy is asleep
	float PoisonDPS = 0; // dps for normal enemies, total remaining damage for bosses

	TurokEnemy( kActor @actor )
	{
		@self = actor;
		m_bMortallyWounded = false;
		m_bDroppedItem = false;
		m_lookAngle = 0;
		m_deathFreezeTime = 0;
	}

	// Smoke39
	int EnemyTier()
	{
		if ( IsBoss() ) return 3;
		// warrior: 28;  raptor: 50;  alien: 50,60;  sergeant: 75
		return Int( self.SpawnParams( SP_HEALTH ) >= 25 ) + Int( self.SpawnParams( SP_HEALTH ) >= 65 );
	}
	bool CanRespawn()
	{
		if ( Opt::EnemyRespawn == RS_AUTO )
			return EnemyTier() < Game.GetDifficulty();
		return EnemyTier() < Opt::EnemyRespawn-1;
	}
	bool IsBoss()
	{
		switch ( self.Type() )
		{
			case AT_AIBOSS_HUMMER:  case AT_AIBOSS_HUNTER:
			case AT_AIBOSS_MANTIS:  case AT_AIBOSS_TREX:
			case AT_AIBOSS_CAMPAINGER:
				return true;
		}
		return false;
	}

	uint AIFlags( uint def = 0 )
	{
		if ( self.CastToAI() is null ) return def;
		return self.CastToAI().AIFlags();
	}

	bool CanBeTargeted()
	{
		// make sure we still really exist
		if ( self.IsStale() ) return false;
		// disabled - waiting to ambush (should also have hold trigger anim, but base game tends to skip it)
		// hold trigger anim - level 4 gallery enemies waiting to be "activated"
		if ( self.Flags() & (AF_DEAD | AF_INVINCIBLE | AF_DISABLED | AF_HOLDTRIGGERANIM) != 0 ) return false;
		// dormant - AI suspended (out of range, or incapacitated)
		if ( self.Flags() & AF_DORMANT != 0 && !IsIncapacitated() ) return false;
		// worms and crabs going underground/underwater (new testing indicates otherwise?)
		if ( self.Flags() & AF_SOLID == 0 ) return false;
		// skip if respawning, or non-thinking (hanging bodies on level 8)
		if ( AIFlags() & (AIF_REGENERATE | AIF_NOTHINK) != 0 ) return false;
		// skip if shielded
		if ( self.ImpactType() == IT_FORCEFIELD ) return false;
		return true;
	}
	// can this enemy be affected at all by sunfire pods
	// (may return true if bonus damage applies, even if IncapCanDisable() can't disable enemy)
	// same as CanBeTargeted(), minus force field protection, and with boss check and sedation check
	bool CanBeDazed()
	{
		if ( self.IsStale() ) return false;
		if ( IsBoss() ) return false;
		if ( bSedated ) return false;
		if ( self.Flags() & (AF_DEAD | AF_INVINCIBLE | AF_DISABLED | AF_HOLDTRIGGERANIM) != 0 ) return false;
		if ( self.Flags() & AF_DORMANT != 0 && !IsIncapacitated() ) return false;
		if ( self.Flags() & AF_SOLID == 0 ) return false;
		if ( AIFlags() & (AIF_REGENERATE | AIF_NOTHINK) != 0 ) return false;
		return true;
	}

	// Smoke39 - target leading, aim explosives at feet, more nuanced angle limiting
	void SpawnProj( const kStr &in proj, const kVec3 &in spawnLoc,
		bool bExplosive = false, bool bLead = false, float projSpeed = 0,
		float leftLimit = Math::Deg2Rad(-90), float rightLimit = Math::Deg2Rad(90) )
	{
		kActor @target = self.GetTarget();
		if ( target is null )
			@target = Player.Actor().CastToActor();
		if ( target is null )
		{
			self.SpawnFx( proj, spawnLoc );
			return;
		}

		// vector to target
		kVec3 dif = target.Origin() - self.GetTransformedVector( spawnLoc );

		// aim explosives at feet
		if ( !bExplosive )
			dif.z += 0.5f * target.Height();

		// lead target
		if ( bLead && Game.GetDifficulty() > DIFFICULTY_HARD )
		{
			float dist = dif.Unit();
			float t = dist / projSpeed;
			dif += target.Movement() * kVec3(1,1,0) * (t / GAME_DELTA_TIME);
		}

		// smallest angles from our orientation to aim at target
		kAngle yaw = dif.ToYaw() - self.Yaw();
		kAngle pitch = dif.ToPitch();// - self.Pitch();

		// clamp to max offset, and add our rotation
		yaw = Math::Clampf( yaw, leftLimit, rightLimit ) + self.Yaw();
//		pitch = Math::Clampf( pitch, -limit, limit ) + self.Pitch();

		self.SpawnFx( proj, spawnLoc, kQuat( pitch, 1,0,0 ) * kQuat( -yaw, 0,0,1 ) );
	}

	/*
	==============================================================
	OnTick
	==============================================================
	*/

	// Smoke39 - completely redone
	void OnTick(void)
	{
		if ( AIFlags() & AIF_REGENANIMDELAY != 0 )
			Reset();

		FixCollisionVolume();
		if ( bLocationalDamageDebug && self.Flags() & AF_DEAD == 0 && self.CanSee(Player.Actor()) )
			SpawnHeadLine();

		if ( bDeathTaunt )
		{
//			Taunt_EnemyDeath( self, DeathDamDef );
			TauntSystem::EnemyDeath( this, DeathDamDef );
			bDeathTaunt = false;
			@DeathDamDef = null;
		}
//		if ( self.Flags() & AF_DEAD != 0 && !self.OnGround() )
//			PlayTaunt( Taunt_Kill_Fall, 0 );

		if ( self.CanSee(Player.Actor()) )
		{
			PlayerVisibleTime = Math::Min( PlayerVisibleTime + GAME_DELTA_TIME, 1.0f );
			// only increment if the player is in front of us
//			kVec3 dif = (Player.Actor().Origin() - self.Origin()) * kVec3(1,1,0);
//			kVec3 facing = kVec3( 0, 1, 0 ) * kQuat( -self.Yaw(), 0,0,1 );
//			if ( dif.Dot(facing) > 0 )
//				PlayerSightedTime = Math::Min( PlayerSightedTime + GAME_DELTA_TIME, 1.0f );
		}
		else
		{
			PlayerVisibleTime = Math::Max( PlayerVisibleTime - GAME_DELTA_TIME * 0.25f, 0.0f );
//			PlayerSightedTime = Math::Max( PlayerSightedTime - GAME_DELTA_TIME * 0.25f, 0.0f );
		}

		BlownIntoWater();
		// NOTE: don't override incapacitation anim speed with difficulty speedup
		if ( !UpdateIncapacitation() )
			DifficultySpeedup();

		if ( self.Flags() & AF_DEAD != 0 )
		{
			// respawn suppression
			if ( self.CastToAI() !is null && !CanRespawn() )
			{
				self.CastToAI().AIFlags() |= AIF_RESSURECT;
				self.MarkPersistentBit( false );
			}

			UpdateDeathFreeze();
		}
		else
			@oldTarget = self.GetTarget();

		ApplyBonusDamage();
		UpdatePoison();
		Ablaze();
		AlienFreeze();

		LastScaledTick = PlayLoop.Ticks();
	}

	// Smoke39 - moved to its own function, and added nuke version
	bool UpdateDeathFreeze()
	{
		if ( m_deathFreezeTime <= 0 ) return false;
		m_deathFreezeTime -= GAME_DELTA_TIME;
		if ( m_deathFreezeTime > 0 ) return true;
		if ( bNuke )
		{
			self.PlaySound( "sounds/shaders/explosion_2.ksnd" );
			Game.SpawnFx( "fx/T2/Nuke/Death.kfx", self.Origin(), self.SectorIndex() );
		}
		else
			Game.SpawnFx( "fx/freeze_explosion.kfx", self.Origin(), self.SectorIndex() );
		self.Remove();
		TauntSystem::Death_Shockwave();
		return true;
	}

	// Smoke39
	void FixCollisionVolume()
	{
		if ( self.Height() != oldHeight )
		{
			if ( self.Flags() & AF_DEAD == 0 )
			{
				// NOTE - don't FixDeadHeight() - we still want to be easy to hit
				if ( bSedated )
					self.Height() = self.StepHeight();
				else
					FixHeight();
			}
			else
				FixDeadHeight();
			oldHeight = self.Height();
		}
		if ( self.Radius() != oldRadius )
		{
			FixRadius();
			oldRadius = self.Radius();
		}
	}
	void InitHeight()
	{
		// height is reduced by some factor of Z scale until enemy moves
		// increment height here to correct for this
	}
	void FixHeight()
	{
	}
	void FixDeadHeight()
	{
	}
	void FixRadius()
	{
	}

	// Smoke39
	void ApplyBonusDamage()
	{
		if ( BonusDamage < 1 ) return;
		if ( self.Flags() & AF_DEAD == 0 )
		{
			bApplyingBonusDamage = true;
			self.InflictGenericDamage( self, BonusDamage );
			bApplyingBonusDamage = false;
		}
		BonusDamage = 0;
	}

	// Smoke39
	void Ablaze()
	{
		// skip all this crap if we're not actually burning or smoldering
		if ( burnFactor <= 0 && burnSmokeFactor <= 0 )
		{
			// but still apply damage from flares and stun overflow
			ApplyBurnDamage();
			return;
		}

		float f, g;
		bool bWater = self.GetWaterLevel() > WLT_OVER;

		// fire goes out after 1 second of no fire damage
		if ( flameTick != self.GameTicks() )
		{
			f = g = GAME_DELTA_TIME;

			// burn out slower when dead
			if ( self.Flags() & AF_DEAD != 0 )
			{
				f *= 0.5f;
				g *= Math::Lerp( 0.05f, 0.5f, burnSmokeFactor );
			}

			// burn out even slower during nuke death
			if ( bNuke )
			{
				f /= 2.5f;
				g /= 2.5f;
			}

			// extinguish faster in water
			if ( bWater )
			{
				f *= 2;
				g *= 2;
			}

			burnFactor = Math::Max( burnFactor - f, 0.0f );
			burnSmokeFactor = Math::Max( burnSmokeFactor - g, 0.0f );
		}

		// 1.5 damage per tick at full blaze
		IncBurnAccumulator( 1.5f * burnFactor * burnFactor );
		ApplyBurnDamage();

		// spawn flames
		kVec3 r = FlameRadii();
		kVec3 o = FlameOffset();
		if ( !bWater )
		{
			burnParticleAccumulator += burnFactor * FlameDensity(r) * Game.GetGameSpeed();
			burnParticleAccumulator = SpawnFireParticle( "fx/TPlus/OnFire.kfx", o, r, burnParticleAccumulator, 0.1f );
		}

		// spawn smoke
		f = bWater ? 20 : 10;
		kVec3 rs( Math::Max( r.x - f, 0.0f ), Math::Max( r.y - f, 0.0f ), Math::Max( r.z - f, 0.0f ) );
		o.z += r.z - rs.z;
		// randomize smoke rate less as smoke factor decreases
		f = Math::Lerp( 1.0f, Math::RandRange( 0.5f, 1.0f ), burnSmokeFactor );
		if ( !bWater )
			f *= 0.25f;
		burnSmokeAccumulator += Math::FakeSqrt( burnSmokeFactor ) * FlameDensity( r/*s*/ ) * f
		                      * Game.GetGameSpeed();
		burnSmokeAccumulator = SpawnFireParticle(
			bWater ? "fx/TPlus/AlienWep/Flame_Steam.kfx" : "fx/TPlus/OnFire_Smoke.kfx",
			o, rs, burnSmokeAccumulator, 0, Math::FakeSqrt( burnSmokeFactor ), !bWater );

		// steam sound
		if ( bWater )
		{
			burnSteamAccumulator += burnFactor;
			if ( burnSteamAccumulator >= 1 )
			{
				self.PlaySound( "sounds/shaders/TPlus/AlienWep/Flame_Steam.ksnd" );
				burnSteamAccumulator -= 1;
			}
		}
	}

	void ApplyBurnDamage()
	{
		if ( burnAccumulator < 1 ) return;
		// bonuses are already built in for accuracy
		// so treat like bonus damage so it won't have bonuses re-applied
		bApplyingBonusDamage = true;
		int target = int( burnAccumulator );
		burnAccumulator -= target;
		int dam = target;
		switch ( DamageDifficulty() )
		{
			case DIFFICULTY_EASY:
				dam = Math::iCeil( dam / 1.4f );
				// scaled damage has holes
				// e.g., nothing gets scaled to 3: 2 * 1.4 = 2.8 (2), 3 * 1.4 = 4.2 (4)
				if ( int( dam * 1.4f ) > target )
				{
					self.InflictGenericDamage( self, 1 );
					dam--;
				}
				break;
			case DIFFICULTY_HARD:
			case DIFFICULTY_HARDCORE:
				dam = int( dam / 0.7f );
		}
		self.InflictGenericDamage( self, dam );
		bApplyingBonusDamage = false;
	}

	float SpawnFireParticle( kStr fx, kVec3 offset, kVec3 radii, float accumulator,
		float rRand = 0, float vRand = 1, bool bTop = false )
	{
		kVec3 v;
		while ( accumulator >= 1.0f )
		{
			v = kVec3(0,0,1).Randomize( vRand );
			v *= (1 - rRand) + Math::RandFloat() * rRand;
			if ( bTop )
				v.z = Math::Fabs( v.z );
			v *= radii;
			v += offset;
			self.SpawnFx( fx, v / self.Scale() );
			accumulator -= 1.0f;
		}
		return accumulator;
	}

	kVec3 FlameRadii()
	{
		return kVec3( self.Radius(), self.Radius(), self.Height() * 0.5f );
	}

	kVec3 FlameOffset()
	{
		return kVec3( 0, 0, self.Height() * 0.5f );
	}

	float FlameDensity( kVec3 radii )
	{
		float rSqr = Math::Sqr( (radii.x + radii.y + radii.z) / 3.0f );
		return 4 * Math::pi * rSqr * 0.00005f;
	}

	// global position scorpion should lock onto
	kVec3 TrackPoint()
	{
		kVec3 v = FlameOffset();
		v.z += 0.15f * self.Height();
		return self.Origin() + v * self.Rotation();
	}

	// Smoke39 - alien weapon suction effect
	void AlienFreeze()
	{
		float f, sum = 0;
		int i, q = AlienFreezeTimes.length();
		for ( i = 0;  i < q;  i++ )
		{
			AlienFreezeTimes[i] += 1.35f * GAME_DELTA_TIME;
			if ( AlienFreezeTimes[i] > 1.0f )
			{
				AlienFreezeTimes.removeAt(i);
				AlienFreezeLocs.removeAt(i);
				--i;
				--q;
			}
			else
				sum += AlienFreezeForce( AlienFreezeTimes[i] );
		}

		if ( sum <= 0 )
			return;

		for ( i = 0;  i < q;  i++ )
		{
			f = AlienFreezeForce( AlienFreezeTimes[i] );
			self.Origin() += (AlienFreezeLocs[i] - self.Origin())  // direction to pull in
			               * 0.25f * f  // how hard to pull
			               * f / sum;   // weighted by all alien freeze forces
		}
	}

	// Smoke39
	float AlienFreezeForce( float f )
	{
//		return f*f*f;
		return f*f;
	}

	// Smoke39
	void BlownIntoWater()
	{
/*		// water level seems to stay at 0 when landing in shallow water for some reason
		bool bInWater = self.GetWaterLevel() > WLT_OVER ||
			(GetAreaFlags(self) & AAF_SHALLOWWATER_COMP == AAF_SHALLOWWATER_COMP && self.OnGround());

		if ( self.Flags() & AF_DEAD == 0 )
		{
			bWasInWater = bInWater;
			return;
		}

		// in water
		if ( bInWater )
		{
			self.Velocity() *= 0.9;
			// entering water
			if ( !bWasInWater )
			{
				if ( GetAreaFlags(self) & AAF_ANTIGRAVITY == 0 )
				{
					self.SpawnFx( "fx/generic_96.kfx", Math::vecZero );
					self.PlaySound( "sounds/shaders/water_splash_1.ksnd" );
				}
				self.Velocity() *= 0.6;
				self.Gravity() = 0.25;
			}
		}
		// exiting water - reset gravity
		else if ( bWasInWater )
			self.Gravity() = 0.5;

		bWasInWater = bInWater;
*/	}

	// Smoke39 - estimate agitation
	bool IsAgitated()
	{
		switch ( self.AnimState().PlayingID() )
		{
			// combative actions not covered by AI flags
			case anim_aiPurlinSpawnDrop:  case anim_aiGruntSpawnDrop:
			case anim_aiTeleportIn:  case anim_aiTeleportOut:
				break;

			default:
				// not doing something combative
				if ( AIFlags() & (AIF_RUNNING | AIF_ATTACKING) == 0 )
				{
					// stay agitated for a while (but don't reset timer)
					return PlayLoop.Ticks() - LastAgitatedTick < int( 12 / GAME_DELTA_TIME );
				}
				// else doing something combative
		}

		// agitated and doing something combative
		LastAgitatedTick = PlayLoop.Ticks();
		return true;
	}

	// Smoke39
	// returns true if enemy is disabled (e.g., convulsing)
	// may still be affected and take bonus damage even if this returns false
	bool UpdateIncapacitation()
	{
		if ( self.Flags() & AF_DEAD != 0 )
		{
			// if animation is still locked while dead, we died in our sleep (unless it was shockwave weapon)
			if ( self.AnimState().flags & ANF_NOINTERRUPT != 0 && m_deathFreezeTime <= 0 )
			{
				// prevent respawning enemies from being frozen,
				// and allow subsequent explosion death anims to play
				self.AnimState().flags &= ~ANF_NOINTERRUPT;
				// drop item, since death anim isn't playing to trigger it
				// we do this here instead of CancelIncapacitation() because m_bMortallyWounded
				//   doesn't get set until the end of or right after OnDeath()
				DropItem( self, 0, 0, 0, 0 );
			}
			return false;
		}
		bool bDisabled = UpdateSedation();
		if ( StunTime <= 0 && DazeTime <= 0 )
			return bDisabled;
		bDisabled = UpdateStun( bDisabled ) || bDisabled;
		bDisabled = UpdateDaze( bDisabled ) || bDisabled;
		// no longer stunned or dazed - stop holding idle anim
		if ( !IsIncapacitated() )
			self.AnimState().flags &= ~ANF_NOINTERRUPT;
		return bDisabled;
	}
	// disable all incapacitation effects, called in OnDeath()
	void CancelIncapacitation( kDictMem@ deathDamDef )
	{
		if ( IsIncapacitated() )
		{
			// stop holding stun/daze anim (but block death anim if asleep, unless we were blown up)
			if ( !bSedated || (deathDamDef !is null && GetBool( deathDamDef, "bExplode" )) )
				self.AnimState().flags &= ~ANF_NOINTERRUPT;

			StunTime = 0;
			StunOverflow = 0;
			DazeTime = 0;
		}
		// tranq only incaps once full, so clear it out even if not incap'd
		UnSedate();
	}
	// enemy is susceptible to bonus damage (but may not necessarily be disabled)
	bool IsIncapacitated()
	{
		return StunTime > 0 || DazeTime > 0 || bSedated;
	}

	// can this enemy be disabled by incapacitators
	// this only applies to convulsions or dazing, not whether the actor can be affected at all (may still take bonus damage)
	bool IncapCanDisable()
	{
		// bosses take bonus damage, but don't get disabled
		if ( IsBoss() )
			return false;
		// don't disable while teleporting, to prevent AI from locking up
		if ( AIFlags() & (AIF_TELEPORTING | AIF_TELEPORTAWAY | AIF_TELEPORTMOVESLOW) != 0
		  || self.AnimState().IsPlaying( anim_aiTeleportIn )
		  || self.AnimState().IsPlaying( anim_aiTeleportOut ) )
		{
			bStunTeleportHack = true;
			return false;
		}
		// don't disable for one tick after teleporting, to make sure the AI's fully cleared up its teleportation shit
		else if ( bStunTeleportHack )
		{
			bStunTeleportHack = false;
			return false;
		}
		return true;
	}
	// disable enemy, locking them into some kind of incapacitated anim
	// TODO: rename this to better match semantics of IsIncapacitated() and IncapCanDisable()
	void Incapacitate( int anim, float animRate )
	{
		self.Flags() |= AF_DORMANT;
		if ( !self.AnimState().IsPlaying(anim) )
			self.AnimState().Set( anim, animRate, ANF_LOOP | ANF_NOINTERRUPT | ANF_ROOTMOTION );
		else
		{
			self.AnimState().ChangeSpeed( animRate );
			self.AnimState().flags |= ANF_NOINTERRUPT;
		}
		self.Yaw() = StunYaw; // AF_DORMANT isn't always enough to prevent turning to face player
		self.SetTarget( null ); // prevent head tracking
	}

	bool UpdateSedation()
	{
		if ( Sedation <= 0 ) return false;

		int anim;
		float rate, tween;
		KnockoutAnim( anim, rate, tween );
		if ( !self.AnimState().CheckAnimID( anim ) )
		{
			Sedation = 0;
			return false;
		}

		if ( (Sedation >= 1 || bSedated) && !self.AnimState().IsPlaying( anim ) && IncapCanDisable() )
		{
			self.AnimState().flags &= ~ANF_NOINTERRUPT; // allow sleep anim to interrupt stun/daze anim
			self.AnimState().Blend( anim, rate, tween, ANF_LOOP | ANF_NOINTERRUPT | ANF_ROOTMOTION );
			bSedated = true;
		}

		// this should be a steady DPS that runs out in sync with Sedation
		// but cap to 100% of remaining in case of rounding errors as Sedation approaches 0
		if ( SedationOverflow > 0 )
			SedationOverflow -= Math::Min( SedationOverflow / (Sedation * 15) * GAME_DELTA_TIME, SedationOverflow );

		Sedation -= GAME_DELTA_TIME / 15;
		if ( Sedation <= 0 )
			UnSedate();

		if ( self.AnimState().IsPlaying(anim) )
		{
			if ( PlayLoop.Ticks() % 15 == 0 && PlayLoop.Ticks() != LastScaledTick && SnoozeTime() )
			{
				Game.SpawnFx( "fx/T2/Tranq/Snooze.kfx", self, kVec3( 0, 0, 0.5f ), SnoozeLoc(),
					kQuat( Math::Deg2Rad( PlayLoop.Ticks() / 15 * 45 ), 0,0,1 ) );
			}
			self.AnimState().ChangeSpeed( rate );
			self.AnimState().flags |= ANF_NOINTERRUPT | ANF_ROOTMOTION;
			self.Flags() |= AF_DORMANT;
			self.Yaw() = StunYaw; // AF_DORMANT isn't always enough to prevent turning to face player
			self.SetTarget( null ); // prevent head tracking
			return true;
		}

		return false;
	}
	// some enemies like insects simply take damage from tranq darts
	bool TranqDealsDamage()
	{
		return false;
	}
	void KnockoutAnim( int&out anim, float&out rate, float&out tween )
	{
		if ( self.AnimState().CheckAnimID( anim_AI_Knockout ) )
		{
			anim = anim_AI_Knockout;
			tween = 15;
		}
		else
		{
			anim = anim_aiDeathStand;
			tween = self.AnimSpeed() * 2;
		}
		rate = self.AnimSpeed() * 2;
	}
	bool SnoozeTime()
	{
		return self.AnimState().TrackTime() > 0.75f;
	}
	kVec3 SnoozeLoc()
	{
		return self.Origin() + kVec3( 0, 0, self.Height() );
	}
	void UnSedate()
	{
		Sedation = 0;
		SedationOverflow = 0;
		if ( !bSedated ) return;
		bSedated = false;
		// if we died in our sleep, just keep lying there
		if ( self.Flags() & AF_DEAD != 0 )
		{
			// can now fully reduce collision height
			FixDeadHeight();
			oldHeight = self.Height();
			return;
		}
		self.AnimState().flags &= ~ANF_NOINTERRUPT; // allow wakeup anim to interrupt sleep anim
		self.AnimState().Blend( anim_aiStanding, self.AnimSpeed(), 45, ANF_ROOTMOTION );
	}

	void UpdatePoison()
	{
		if ( PoisonDPS <= 0 ) return;
		// NOTE: don't use IncBurnAccumulator() because we don't want bonus damage applied
		// (being incapacitated wouldn't make poison more effective,
		//  and power core is applied on hit, not to DOT)
		if ( IsBoss() )
		{
			float amt = Math::Min( (100 + PoisonDPS) * GAME_DELTA_TIME / 15, PoisonDPS );
			burnAccumulator += amt * DifficultyDamageScale();
			PoisonDPS -= amt;
			if ( !BossPoisonActive() ) self.RunFxEvent( "PoisonEnd" );
		}
		else
		{
			// should be cleared in PoisonDeath(), but since this lasts indefinitely, make absolutely sure just in case some subclass doesn't call PoisonDeath()
			if ( self.Flags() & AF_DEAD != 0 )
			{
				PoisonDPS = 0;
				return;
			}
			burnAccumulator += PoisonDPS * GAME_DELTA_TIME * DifficultyDamageScale();
			PoisonDPS *= 1 + GAME_DELTA_TIME;
		}
	}
	// enough poison remains to not have started fade out actor fx
	bool BossPoisonActive()
	{
		return PoisonDPS > 100.0f / 15;
	}

	bool UpdateStun( bool bSuperceded )
	{
		if ( StunTime <= 0 )
			return false;

		if ( StunOverflow > 0 )
		{
			// this should be a steady DPS that runs out in sync with StunTime
			// but cap to 100% of remaining in case of rounding errors as StunTime approaches 0
			float dam = Math::Min( StunOverflow / StunTime * GAME_DELTA_TIME, StunOverflow );
			IncBurnAccumulator( dam );
			StunOverflow -= dam;
			kVec3 r = FlameRadii();
			kVec3 o = FlameOffset();
			StunSmokeAccumulator += Math::Sqrt( dam * 10 ) * FlameDensity( r ) * Game.GetGameSpeed();
			StunSmokeAccumulator = SpawnFireParticle( "fx/T2/ChargeDart/Stun_Smoke.kfx", o, r, StunSmokeAccumulator );
		}

		// count down stun time
		StunTime -= GAME_DELTA_TIME;
		if ( StunTime <= 0 )
		{
			StunTime = 0;
			StunOverflow = 0;
			return false;
		}

		// apply stun effects
		StunEffects();

		// sedation supercedes convulsions
		if ( bSuperceded )
			return false;
		// check if we can be fully disabled
		if ( !IncapCanDisable() )
			return false;

		Incapacitate( anim_aiStanding, 0.35f );
		return true;
	}
	void StunEffects()
	{
		self.PlaySound( "sounds/shaders/T2/ChargeDart/Zap_" + (1 + Math::RandMax(5)) + ".ksnd" );

		kVec3 r = FlameRadii();
		kVec3 o = FlameOffset();
		StunParticleAccumulator += 2 * FlameDensity( r ) * Game.GetGameSpeed();
		StunParticleAccumulator = SpawnFireParticle( "fx/T2/ChargeDart/Stun.kfx", o, r, StunParticleAccumulator, 0.1f );
	}

	bool UpdateDaze( bool bSuperceded )
	{
		if ( DazeTime <= 0 )
			return false;
		// count down daze time
		DazeTime -= GAME_DELTA_TIME;
		if ( DazeTime <= 0 )
		{
			DazeTime = 0;
			return false;
		}

		// skip even the sparkles if we're asleep
		if ( bSedated )
			return false;

		// spawn daze effects
		DazeEffects();

		// convulsing supercedes dazed waver
		if ( bSuperceded )
			return false;
		// check if we can be fully disabled
		if ( !IncapCanDisable() )
			return false;

		SetDazeAnim();
		return true;
	}
	void SetDazeAnim()
	{
		Incapacitate( self.SpawnFlags2() & ASF2_ALTERNATEMOVES != 0
			&& self.AnimState().CheckAnimID( anim_aiGruntStandAlt )
			? anim_aiGruntStandAlt : anim_aiStanding, 2 );
	}
	void DazeEffects()
	{
		if ( PlayLoop.Ticks() != LastScaledTick )
			self.SpawnFx( "fx/T2/Sunfire/Daze.kfx", DazeOffset() );
	}
	kVec3 DazeOffset()
	{
		kVec3 v = FlameOffset();
		v.z += self.Height() * 0.25f;
		v.y -= self.Radius();
		return v / self.Scale();
	}

	// Smoke39
	void DifficultySpeedup()
	{
		// no speedup out of combat
		if ( !IsAgitated() )
		{
			self.AnimState().ChangeSpeed( self.AnimSpeed() );
			return;
		}

		switch ( self.AnimState().PlayingID() )
		{
			// keep these from being sped up on hardcore
			// idle
			case anim_aiStanding: case anim_aiGruntStandAlt:
			// death
			case anim_aiDeathKnockback1:  case anim_aiDeathKnockback2:
			case anim_aiDeathKnockback3:  case anim_aiDeathKnockback4:
			case anim_aiDeathStand:    case anim_aiGruntDeathStandAlt:
			case anim_aiDeathViolent:  case anim_aiGruntDeathViolentAlt:
			case anim_aiDeathRunning:  case anim_aiGruntDeathRunningAlt:
				self.AnimState().ChangeSpeed( self.AnimSpeed() );
				break;

			// MINOR SPEEDUP
			// ambush
			// hardcore neglects these, so always speed them up
			// these only have two speeds: normal (easy/normal/hard without speedup)
			// and faster (easy/normal/hard with speedup, hardcore with/without speedup)
			case anim_aiPurlinSpawnDrop: case anim_aiGruntSpawnDrop:
				if ( Opt::bEnemySpeedup || Game.GetDifficulty() >= DIFFICULTY_HARDCORE )
					self.AnimState().ChangeSpeed( self.AnimSpeed() * FastScale() );
				break;

			// AVERAGE SPEEDUP
			// walking, running
			case anim_aiWalking:  case anim_aiGruntWalkAlt:
			case anim_aiRunning:  case anim_aiGruntRunAlt:
			// swimming
			case anim_aiSwim1:  case anim_aiSwim2:  case anim_aiSwim3:  case anim_aiSwim4:
			case anim_aiSwim5:  case anim_aiSwim6:  case anim_aiSwim7:  case anim_aiSwim8:
			case anim_aiSwim9:  case anim_aiSwim10: case anim_aiSwim11:
				if ( Opt::bEnemySpeedup ) self.AnimState().ChangeSpeed( self.AnimSpeed() * FasterScale() );
				break;

			// MAXIMUM SPEEDUP
			// turning
			case anim_aiTurn_L_Stand:  case anim_aiTurn_R_Stand:  case anim_aiTurn_B_Stand:
			case anim_aiGruntTurn_L_StandAlt:  case anim_aiGruntTurn_R_StandAlt:  case anim_aiGruntTurn_B_StandAlt:
			case anim_aiTurn_L_Walk:  case anim_aiTurn_R_Walk:  case anim_aiTurn_B_Walk:
			case anim_aiGruntTurn_L_WalkAlt:  case anim_aiGruntTurn_R_WalkAlt:  case anim_aiGruntTurn_B_WalkAlt:
			case anim_aiTurn_L_Run:  case anim_aiTurn_R_Run:  case anim_aiTurn_B_Run:
			case anim_aiGruntTurn_L_RunAlt:  case anim_aiGruntTurn_R_RunAlt:  case anim_aiGruntTurn_B_RunAlt:
			// melee attacks
			case anim_aiMelee1:  case anim_aiMelee2:  case anim_aiMelee3:  case anim_aiMelee4:
			case anim_aiMelee5:  case anim_aiMelee6:  case anim_aiMelee7:  case anim_aiMelee8:
			case anim_aiMelee9:  case anim_aiMelee10: case anim_aiMelee11: case anim_aiMelee12:
			case anim_aiMelee13: case anim_aiMelee14:
			case anim_aiAltMelee1:  case anim_aiAltMelee2:  case anim_aiAltMelee3:  case anim_aiAltMelee4:
			case anim_aiAltMelee5:  case anim_aiAltMelee6:  case anim_aiAltMelee7:  case anim_aiAltMelee8:
			case anim_aiAltMelee9:  case anim_aiAltMelee10: case anim_aiAltMelee11: case anim_aiAltMelee12:
			case anim_aiAltMelee13: case anim_aiAltMelee14:
			// ranged attacks
			case anim_aiRangeAttack1:  case anim_aiRangeAttack2:  case anim_aiRangeAttack3:
			case anim_aiRangeAttack4:  case anim_aiRangeAttack5:  case anim_aiRangeAttack6:
			case anim_aiRangeAttack7:  case anim_aiRangeAttack8:  case anim_aiRangeAttack9:
			case anim_aiRangeAttack10:
			// shaman teleportation
			case anim_aiTeleportIn:
			case anim_aiTeleportOut:
				if ( Opt::bEnemySpeedup ) self.AnimState().ChangeSpeed( self.AnimSpeed() * FastestScale() );
				break;

			// not yet witnessed
/*			case anim_aiLostSight:     Game.PrintLine( "lost sight",   0 );  break;
			case anim_aiReach:         Game.PrintLine( "reach",        0 );  break;
			case anim_aiDodgeRight:    Game.PrintLine( "dodge right",  0 );  break;
			case anim_aiDodgeLeft:     Game.PrintLine( "dodge left",   0 );  break;
			case anim_aiDodgeCrouch:   Game.PrintLine( "dodge crouch", 0 );  break;
			case anim_aiWounded:       Game.PrintLine( "wounded",      0 );  break;
			case anim_aiTurn_L_Wound:  Game.PrintLine( "turn L wound", 0 );  break;
			case anim_aiTurn_R_Wound:  Game.PrintLine( "turn R wound", 0 );  break;
			case anim_aiTurn_B_Wound:  Game.PrintLine( "turn B wound", 0 );  break;
			case anim_stun1:           Game.PrintLine( "stun 1",       0 );  break;
			case anim_stun2:           Game.PrintLine( "stun 2",       0 );  break;
*/
			// completely unknown
			// 126 - seen when grunts fall in early in level 1, but remains when they're dead
			//       also by chronoscepter piece, sniper alley on level 2
			// 125 - seen at the end of level 1 - body decomposing?
			// 128 - seen by the AR on level 2
			// 127 - seen past sniper alley, big cave entrance on level 2
			// 60  - by chronoscepter piece on level 2
			//       by shockwave weapon on level 5
			// 200 - 206 are trigger anims
//			default:
//				Game.PrintLine( ""+ self.AnimState().PlayingID(), 0 );
		}
	}

	float FastScale()    { return 0.75f; }
	float FasterScale()  { return Game.GetDifficulty() < DIFFICULTY_HARDCORE ? 0.625f : 0.375f; }
	float FastestScale() { return Game.GetDifficulty() < DIFFICULTY_HARDCORE ? 0.5f   : 1.0f/3; }

	/*
	==============================================================
	OnSpawn
	==============================================================
	*/

	void OnSpawn(void)
	{
	}

	// Smoke39
	void OnPostBeginLevel()
	{
		// actual height isn't initialized until at least OnBeginLevel()
		InitialHeight = self.Height();
		// prior to 3.0, the actor's height would start lower, then get bumped up as soon as the actor moved
		// this seems to've been fixed, so skip InitHeight(), and, for now, adjust InitialHeight by the old offset (at least, what it seems to be, based on human and pur-lin ambushers on level04.map)
		// I suspect I could get slightly better results if I recalibrated all FixHeight()s to the new, better InitialHeight, but this should do as a quick and dirty fix for now
//		InitHeight();
		InitialHeight -= 2.25f * GAME_SCALE * self.Scale().z;
	}

	void OnSleep()
	{
		// making this contingent on AF_DEAD sometimes causes false negatives
		Reset();
	}

	// called during time between melting and respawning,
	// or when going dormant (which may be respawning the enemy,
	//   but is usually a corpse being purged or a live enemy going dormant normally)
	void Reset()
	{
		m_bMortallyWounded = false;
	}

	/*
	==============================================================
	TurnAngles
	==============================================================
	*/

	void TurnAngles(const float turnSpeed, const float angles)
	{
		float temp = angles;
		float ang = angles;

		if(ang > turnSpeed)
		{
			ang = turnSpeed;
		}
		else if(ang < -turnSpeed)
		{
			ang = -turnSpeed;
		}

		ang *= GAME_FRAME_TIME;
		if(Math::Fabs(ang) > Math::Fabs(temp))
		{
			ang = temp;
		}

		self.Yaw() += ang;
	}

	/*
	==============================================================
	InPlayerProjectilePath
	==============================================================
	*/

	bool InPlayerProjectilePath(const float angleRange)
	{
		if((Player.Actor().PlayerFlags() & PF_FIREDPROJECTILE) != 0)
		{
			if(Math::Fabs(self.GetTurnYaw(Player.Actor().Origin())) < angleRange)
			{
				return true;
			}
		}

		return false;
	}

	/*
	==============================================================
	TossActor
	==============================================================
	*/

	kActor @TossActor(const kStr &in itemName, const float x, const float y, const float z, const kVec3 &in velocity)
	{
		kActor @actor = ActorFactory.Spawn(itemName, x, y, z, 0, self.SectorIndex());

		if(actor is null)
		{
			return null;
		}

		// Smoke39 - size actors based on type
//		actor.Scale().Set(0.35f, 0.35f, 0.35f);
		switch( actor.Type() )
		{
			// size gibs based on enemy size
			case AT_GIB_ALIEN1:   // alien body
			case AT_GIB_ALIEN2:   // alien foot
			case AT_GIB_ALIEN3:   // alien head
			case AT_GIB_STALKER4: // alien torso
				actor.Scale() = self.Scale();
				break;
			case AT_GIB_STALKER1: // leaper body
			case AT_GIB_STALKER2: // leaper foot
			case AT_GIB_STALKER3: // leaper head
			case AT_GIB_STALKER5: // leaper torso
				actor.Scale() = self.Scale() * 0.5f;
				break;
			default:
				actor.Scale().Set(0.35f, 0.35f, 0.35f);
				break;
		}
		actor.ClipFlags() = (CF_DROPOFF|CF_CLIPEDGES|CF_NOCLIPACTORS|CF_COLLIDEFLOORS|CF_COLLIDEHEIGHT);
		actor.Velocity() = velocity;

		actor.Velocity() *= (1.0f / 60.0f);

		switch(actor.Type())
		{
		case AT_GIB_ALIEN3:
			actor.BounceDamp() = 0.6f;
			actor.Gravity() = 0.5f;
			break;

		case AT_GIB_STALKER3:
			actor.BounceDamp() = 0.4f;
			actor.Gravity() = 0.6f;
			break;

		case AT_GIB_STALKER5:
		case AT_GIB_STALKER2:
		case AT_GIB_STALKER1:
			actor.BounceDamp() = 0.3f;
			actor.Gravity() = 0.6f;
			break;

		default:
			actor.BounceDamp() = 0.5f;
			actor.Gravity() = 0.5f;
			break;
		}

		return actor;
	}

	/*
	==============================================================
	TossItem
	==============================================================
	*/

	void TossItem(const kStr &in itemName, const float x, const float y, const float z)
	{
		kActor @item = TossActor(itemName, x, y, z, kVec3(0, 0, 1).Randomize(0.25f).Normalize() * 409.6f);
		item.Flags() |= AF_CASTSHADOW;
		item.RunFxEvent("Item_Spawn");
		// Smoke39
		item.ClipFlags() &= ~CF_DROPOFF; // don't toss off cliffs
		// make smart pickups set their model right away, so the default won't flash for a frame
		ScriptObject@ s = cast<ScriptObject@>( ActorScript(item) );
		if ( s !is null ) s.OnTick();
	}

	/*
	==============================================================
	TossGib
	==============================================================
	*/

	void TossGib(const kStr &in gibActor, const float x, const float y, const float z)
	{
		// Smoke39
		TauntSystem::Death_Gib();

		kVec3 dir = (kVec3(0, 0, 1).Randomize(0.3f).Normalize() * ((Math::Rand() % -2 + 3) * 10.24f)) * 15.0f;
		// Smoke39 - impart some of our velocity onto gibs
		dir += self.Velocity() * 30;
		kVec3 normal, cp;
		kActor @gib;
		TurokGiblet @gibObj;

		self.CheckPosition(kVec3(x, y, z));
		normal = CModel.ContactNormal();

		@gib = TossActor(gibActor, x, y, z, dir);

		dir.Normalize();

		cp = normal.Cross(dir);
		cp.Normalize();

		gib.Yaw() = cp.ToYaw();
		gib.Pitch() = -cp.ToPitch();

		@gibObj = cast<TurokGiblet@>(gib.ScriptObject().obj);

		if(!(gibObj is null))
		{
			gibObj.Spin();
		}
	}

	/*
	==============================================================
	Knockback
	==============================================================
	*/

	void Knockback(kActor @instigator, const float r, const float x, const float y, const float z)
	{
		kVec3 org;
		kVec3 pos;
		kActor @targ;

		if(self.GetTarget() is null)
		{
			return;
		}

		@targ = self.GetTarget();

		org.x = self.Origin().x;
		org.y = self.Origin().y;
		org.z = self.Origin().z + self.Height() * 0.5f;

		pos = targ.GetTransformedVector(kVec3(x, y, z));

		kVec3 dir = pos - org;
		float dist = dir.Unit();

		if(dist > (r * GAME_SCALE + self.Radius()))
		{
			return;
		}

		dir.Normalize();
		dir *= (1.75f*GAME_SCALE);
		dir.z = (0.875f*GAME_SCALE);

		targ.Velocity() += dir;

		if(targ is Player.Actor().CastToActor())
		{
			Player.Actor().Origin().z += GAME_SCALE;
			Player.Actor().PlayerFlags() |= PF_NOAIRFRICTION;

			if(!(Player.Actor().ScriptObject() is null))
			{
				// WARNING: assumes script object is TurokPlayer
				TurokPlayer @p = cast<TurokPlayer@>(Player.Actor().ScriptObject().obj);

				if(p is null)
				{
					return;
				}

				p.m_shoveTime = 0.5f;
				p.m_vShoveVector = org;
			}
		}
	}

	/*
	==============================================================
	SightSound
	==============================================================
	*/

	void SightSound(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	/*
	==============================================================
	Death Sounds
	==============================================================
	*/

	void DeathSound(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	void InjurySound(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	void ViolentSound(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	/*
	==============================================================
	Unused anim callbacks
	==============================================================
	*/

	void Unused23(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	void Unused24(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	void Unused60(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	void Unused94(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	void Unused398(kActor @instigator, const float w, const float x, const float y, const float z)
	{
	}

	/*
	==============================================================
	CauseThump
	==============================================================
	*/

	void CauseThump(kActor @instigator, const float r, const float x, const float y, const float z)
	{
		kActor @actor = ActorFactory.Spawn("QuakeSource", 0, 0, 0, 0, self.SectorIndex());
		TurokQuakeSource @quake;

		if(actor is null)
		{
			return;
		}

		@quake = cast<TurokQuakeSource@>(actor.ScriptObject().obj);

		if(quake is null)
		{
			return;
		}

		quake.SetupThump(self.GetTransformedVector(kVec3(x, y, z)), r);
	}

	/*
	==============================================================
	TriggerEvent
	==============================================================
	*/

	void TriggerEvent(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		World.TriggerActorsByTID(instigator, int(w));
	}

	/*
	==============================================================
	FootStepPuff
	==============================================================
	*/

	void FootStepPuff(kActor @instigator, const float a, const float x, const float y, const float z)
	{
		if(a == 0.0f)
		{
			self.SpawnFx("fx/dustcloud_footfall.kfx", kVec3(x, y, z+4.096f));
		}
		else
		{
			self.SpawnFx("fx/dustcloud_bodyfall.kfx", kVec3(x, y, z+4.096f));
		}
	}

	/*
	==============================================================
	SwishSound
	==============================================================
	*/

	void SwishSound(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.PlaySound("sounds/shaders/knife_swish_1.ksnd");
	}

	/*
	==============================================================
	GunFire
	==============================================================
	*/

	void GunFire(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		Sys.Warning("GunFire is being called from base class object!");
	}

	/*
	==============================================================
	Melee anim callbacks
	==============================================================
	*/

	void MeleeVeryWimpy(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Generic_1", kVec3(x, y, z), w);
	}

	void MeleeBluntWeak(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_3", kVec3(x, y, z), w);
	}

	void MeleeBluntMedium(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_5", kVec3(x, y, z), w);
	}

	void MeleeAttack1(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Flesh_3", kVec3(x, y, z), w);
	}

	void MeleeAttack2(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Flesh_5", kVec3(x, y, z), w);
	}

	void MeleeAttack3(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_5", kVec3(x, y, z), w);
	}

	void MeleeBluntWimpy(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_2", kVec3(x, y, z), w);
	}

	void MeleeBluntStrong(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_10", kVec3(x, y, z), w);
	}

	void MeleeBluntVeryStrong(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_15", kVec3(x, y, z), w);
	}

	void MeleeBluntHeavy(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_20", kVec3(x, y, z), w);
	}

	void MeleeBluntVeryHeavy(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.MeleeObject("Damage_Blunt_30", kVec3(x, y, z), w);
	}

	/*
	==============================================================
	BloodGush
	==============================================================
	*/

	void BloodGush(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		const int count = 3;

		if((self.Flags() & AF_NOBLOOD) != 0)
		{
			return;
		}

		kVec3 vel   = self.Velocity();
		kVec3 pos   = self.GetTransformedVector(kVec3(x, y, z));
		kVec3 pos_v = pos - vel;
		kQuat rot   = vel.ToQuat();

		float f = 0.0f;
		kVec3 newPos;

		for(int i = 0; i < count; ++i)
		{
			newPos = pos;
			newPos.Lerp(pos_v, f / 3.0f);

			// Smoke39 - spawn green blood when appropriate
			if ( self.ImpactType() == IT_FLESH_CREATURE )
				Game.SpawnFx("fx/spurt_greenblood.kfx", self, vel, newPos, rot);
			else
				Game.SpawnFx("fx/spurt_blood.kfx", self, vel, newPos, rot);
			f += 1.0f;
		}
	}

	/*
	==============================================================
	TossGib1-8
	==============================================================
	*/

	void TossGib1(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Alien_Head", org.x, org.y, org.z);
		Game.SpawnFx("fx/generic_108.kfx", org, self.SectorIndex());
	}

	void TossGib2(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Alien_Torso", org.x, org.y, org.z);
		Game.SpawnFx("fx/generic_108.kfx", org, self.SectorIndex());
	}

	void TossGib3(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Alien_Feet", org.x, org.y, org.z);
		// Smoke39 - spawn all 6 hands/feet
		TossGib("Gib_Alien_Feet", org.x, org.y, org.z);
		TossGib("Gib_Alien_Feet", org.x, org.y, org.z);
		TossGib("Gib_Alien_Feet", org.x, org.y, org.z);
		TossGib("Gib_Alien_Feet", org.x, org.y, org.z);
		TossGib("Gib_Alien_Feet", org.x, org.y, org.z);
		Game.SpawnFx("fx/generic_108.kfx", org, self.SectorIndex());
	}

	void TossGib4(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Alien_Body", org.x, org.y, org.z);
		Game.SpawnFx("fx/generic_108.kfx", org, self.SectorIndex());
	}

	void TossGib5(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Stalker_Head", org.x, org.y, org.z);
	}

	void TossGib6(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Stalker_Torso", org.x, org.y, org.z);
	}

	void TossGib7(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Stalker_Feet", org.x, org.y, org.z);
		// Smoke39 - spawn all 4 feet
		TossGib("Gib_Stalker_Feet", org.x, org.y, org.z);
		TossGib("Gib_Stalker_Feet", org.x, org.y, org.z);
		TossGib("Gib_Stalker_Feet", org.x, org.y, org.z);
	}

	void TossGib8(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		kVec3 org = self.GetTransformedVector(kVec3(x, y, z));
		TossGib("Gib_Stalker_Body", org.x, org.y, org.z);
	}

	/*
	==============================================================
	ExplosionSfx2
	==============================================================
	*/

	void ExplosionSfx2(kActor @instigator, const float w, const float x, const float y, const float z)
	{
		self.PlaySound("sounds/shaders/explosion_2.ksnd");
	}

	/*
	==============================================================
	DropItem
	==============================================================
	*/

	// Smoke39 - rewritten to use T+ setting instead of Game.EnemiesAlwaysDropItems()
	void DropItem( kActor @instigator, const float w, const float x, const float y, const float z )
	{
		if ( m_bDroppedItem )
			return;
		m_bDroppedItem = true;

		kVec3 org = self.GetTransformedVector( kVec3(x,y,z) );
		const uint spawnFlags = self.SpawnFlags2();

		if ( DropAmmo() )
		{
			if ( spawnFlags & ASF2_DROPITEM_MASK1 != 0 )
				TossItem( "Ammo_ExpShells_Pickup", org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK2 != 0 )
				TossItem( "Ammo_Grenade_Pickup", org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK8 != 0 )
				TossItem( "Ammo_MiniGunAmmo_Pickup", org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK10 != 0 )
				TossItem( "Ammo_Rockets_Pickup", org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK11 != 0 )
				TossItem( "Ammo_Shells_Pickup", org.x, org.y, org.z );
			// Smoke39 - don't drop cells until player has a proper energy weapon
			if ( spawnFlags & ASF2_DROPITEM_MASK12 != 0 && PlayerHasRealEnergyWeapon() )
				TossItem( "Ammo_Cell_Pickup", org.x, org.y, org.z );
			// Smoke39 - downgrade large cells to small until player has a proper energy weapon
			if ( spawnFlags & ASF2_DROPITEM_MASK13 != 0 )
			{
				if ( PlayerHasRealEnergyWeapon() )
					TossItem( "Ammo_LargeCell_Pickup", org.x, org.y, org.z );
				else
					TossItem( "Ammo_SmallCell_Pickup", org.x, org.y, org.z );
			}
			if ( spawnFlags & ASF2_DROPITEM_MASK14 != 0 )
				TossItem( "Ammo_Clip_Pickup", org.x, org.y, org.z );
		}
		// Smoke39 - add an exception for hand grenades if the player doesn't have the GL yet
		// also downgrade large cells to small, rather than eliminating altogether
		else
		{
			if ( spawnFlags & ASF2_DROPITEM_MASK2 != 0 && Opt::bHandGrenades && !PlayerHasGL() )
				TossItem( "Ammo_Grenade_Pickup", org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK13 != 0 )
				TossItem( "Ammo_SmallCell_Pickup", org.x, org.y, org.z );
		}
		if ( DropHealth() )
		{
			if ( spawnFlags & ASF2_DROPITEM_MASK3 != 0 ) TossItem( "Health_Medium", org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK4 != 0 ) TossItem( "Health_Full",   org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK5 != 0 ) TossItem( "Health_Ultra",  org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK6 != 0 ) TossItem( "Health_Small",  org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK7 != 0 ) TossItem( "Health_Large",  org.x, org.y, org.z );
			if ( spawnFlags & ASF2_DROPITEM_MASK9 != 0
				&& ( self.Flags() & AF_WOUNDEDMORTALLY != 0 || m_bMortallyWounded )
				&& Math::RandMax(100) > 85 )
					TossItem( "Health_MortalWound", org.x, org.y, org.z );
		}
	}

	bool DropAmmo()
	{
		switch ( Opt::ItemDrops )
		{
			case Drop_Auto: return Game.GetDifficulty() < DIFFICULTY_HARD;
			case Drop_All:
			case Drop_Ammo: return true;
		}
		// health, none
		return false;
	}

	bool DropHealth()
	{
		switch ( Opt::ItemDrops )
		{
			case Drop_Auto: return Game.GetDifficulty() < DIFFICULTY_HARD;
			case Drop_All:
			case Drop_Health: return true;
		}
		// ammo, none
		return false;
	}

	/*
	==============================================================
	OnDeath
	==============================================================
	*/

	void OnDeath( kActor@ killer, kDictMem@ damageDef )
	{
		// Smoke39
//		Taunt_EnemyDeath( self, damageDef );
		bDeathTaunt = true;
		@DeathDamDef = damageDef;

		// Smoke39 - moved before damageDef null check
		// haven't tested this, but old way probably caused generic damage to not drop items from respawned enemies
		m_bDroppedItem = false;

		CancelIncapacitation( damageDef );
		FlamingDeath();
		PoisonDeath(); // come second to override flaming death actor fx

		if ( damageDef is null )
			return;

		// Smoke39
		ShockwaveDeath( damageDef ); // moved to its own function, and added nuke subtype
		if ( GetBool( damageDef, "bMortalWound" ) )
			m_bMortallyWounded = true;
	}

	// Smoke39
	void PoisonDeath()
	{
		if ( PoisonDPS <= 0 ) return;
		PoisonDPS = 0;
		self.RunFxEvent( "PoisonDeath" );
	}
	void FlamingDeath()
	{
		if ( burnFactor >= 0.125f )
			self.RunFxEvent( "FireDeath"+ int( burnFactor * 8.0f + 0.5f ) );
	}
	bool ShockwaveDeath( kDictMem@ damDef )
	{
		if ( !GetBool( damDef, "bAccelerator" ) ) return false;
		if ( m_deathFreezeTime > 0 ) return true;
		self.AnimState().flags |= ANF_PAUSED | ANF_NOINTERRUPT;
		self.RunFxEvent( "Enemy_Freeze" );
		if ( GetBool( damDef, "bNuke" ) )
		{
			m_deathFreezeTime = 5.5f;
			bNuke = true;
			burnFactor = 1;
		}
		else
		{
			m_deathFreezeTime = 3;
			Game.SpawnFx( "fx/freeze_start.kfx", self.Origin(), self.SectorIndex() );
		}
		m_deathFreezeTime += Math::RandFloat() * 0.25f;
		return true;
	}

	// Smoke39 - handle new damage properties
	void OnDamage( kActor@ instigator, kDictMem@ damageDef, const int damage )
	{
		if ( bDamageDebug )
		{
			kStr str = (bApplyingBonusDamage ? "bonus " : "damage ") + damage;
			if ( instigator is Player.Actor().CastToActor() )
				str += " player inst";
			if ( damageDef !is null && GetBool( damageDef, "bPlayer" ) )
				str += " bPlayer";
			if ( self.Health() > 0 )
			{
				if ( self.Flags() & AF_DEAD != 0 )
				{
					int t = DamageDebugTick >= 0  ?  self.GameTicks() - DamageDebugTick  :  0;
					str += " TTK "+ (t * GAME_DELTA_TIME) +" "+ t;
					DamageDebugTick = -1;
				}
				// require damage > 0 to not count e.g., charge dart as first hit
				else if ( DamageDebugTick < 0 && damage > 0 )
					DamageDebugTick = self.GameTicks();
			}
			else
				str = "(dead) "+ str;
			Sys.Print( str );
		}

		bool bPlayer = instigator is Player.Actor().CastToActor();

		if ( damageDef !is null )
		{
			bPlayer = bPlayer || GetBool( damageDef, "bPlayer" );

			if ( self.Flags() & AF_DEAD == 0 )
			{
				HandleStunDamage( damageDef );
				HandleTranqDamage( damageDef, bPlayer );
				HandlePoisonDamage( damageDef, bPlayer );
				HandleLocationalDamage( damageDef, bPlayer );
				HandleFlameDamage( damageDef );
				HandleSniperDamage( damageDef, bPlayer );
				HandleMomentumTransfer( damageDef, damage );
				HandleAlienFreeze( damageDef );
			}
			else
				ShockwaveDeath( damageDef );

			HandleFlareDamage( damageDef );
			HandleArrowDamage( damageDef );
		}

		// undo difficulty scaling for normal enemies (will be re-applied by engine when inflicting damage)
		BonusDamage += Math::iCeil( damage / DifficultyDamageScale() * BonusDamageScale(bPlayer) );
	}

	//==========================================================================
	// Smoke39 - new damage type stuff

	// multiple of base damage to add when massive damage power core is active
	float MassiveDamageScale( bool bPlayer )
	{
		return Int( bPlayer && PowerCoreActive() ) * 2;
	}
	// multiple of base damage to add when incapacitated
	float IncapDamageScale()
	{
		return Int( IsIncapacitated() );
	}
	// total multiple of base damage to add from above two combined
	float BonusDamageScale( bool bPlayer )
	{
		return ( MassiveDamageScale( bPlayer ) + IncapDamageScale() ) * Int( !bApplyingBonusDamage );
	}

	void HandleLocationalDamage( kDictMem@ damDef, bool bPlayer )
	{
		int bonus = GetInt( damDef, "HeadBonus" );
		if ( bonus > 0 && (bSedated || Headshot(CModel.InterceptVector()) ) )
		{
			if ( bDamageDebug ) Sys.Print( "headshot "+ bonus );
			BonusDamage += int( bonus * (1 + BonusDamageScale(bPlayer)) );
		}
	}
	bool Headshot( kVec3&in hitLoc )
	{
		return false;
	}
	void SpawnHeadLine()
	{
	}

	void HandleTranqDamage( kDictMem@ damDef, bool bPlayer )
	{
		if ( !GetBool(damDef,"bTranq") ) return;
		if ( TranqDealsDamage() )
		{
			BonusDamage += int( 50 * (1 + MassiveDamageScale( bPlayer )) );
			return;
		}
		// knockout tier is based on current health
		float inc = TranqIncrement( self.Health(), bPlayer );
		Sedation += inc;
		if ( Sedation > 1 )
		{
			// overflow tier is based on max health
			float o = (Sedation - 1) / inc;
			inc = TranqIncrement( self.SpawnParams( SP_HEALTH ), bPlayer );
			SedationOverflow += o * inc;
			// anything beyond 1 overflow gets converted to damage
			// (divide by inc so all enemies take the same amount per dart)
			if ( SedationOverflow > 1 )
			{
				float x = Math::Min( SedationOverflow - 1, inc );
				BonusDamage += Math::iCeil( x / inc * 15 );
			}
			Sedation = 1;
		}
		StunYaw = self.Yaw();
	}
	float TranqIncrement( int health, bool bPlayer )
	{
		int t = IsBoss() ? 4
		      : Int( health >=  70 )
		      + Int( health >= 140 )
		      + Int( health >  450 );
		// 1, 1/2, 1/3, 1/4, 1/5, plus a little extra for decay between shots and to give some leeway
		// (no leeway with massive damage, or else 1 shot would be enough for 4-dart enemies)
		float inc = 1 + MassiveDamageScale( bPlayer );
		if ( t > 0 ) inc /= inc > 1 ? 1.0f + t : (1 + t) * 0.75f;
		return inc;
	}

	void HandlePoisonDamage( kDictMem@ damDef, bool bPlayer )
	{
		if ( !GetBool( damDef, "bPoison" ) ) return;
		float bonus = MassiveDamageScale( bPlayer );
		if ( IsBoss() )
			PoisonDPS += 100 * (1 + bonus);
		else if ( PoisonDPS < 10 * (1 + bonus) )
			PoisonDPS += 10 * (1 + bonus);
		else
			PoisonDPS *= 2 + bonus;
		self.RunFxEvent( "Poisoned" );
	}

	bool HandleSniperDamage( kDictMem@ damageDef, bool bPlayer )
	{
		if ( !GetBool( damageDef, "bSniper" ) )
			return false;

		int damage = GetInt( damageDef, "damage" );

		float dist = (self.Origin() - Player.Actor().Origin()).Unit();
		float bonusDam = damage * Math::Max( (dist - 500) / 500, 0.0f );
		if ( !IsAgitated() )
			bonusDam *= 2;

//		Sys.Warning( ""+ int(100.0f*float(bonusDam+damage)/float(damage)) +"pct" );
		if ( bonusDam >= 1 )
		{
			BonusDamage += int( bonusDam * (1 + BonusDamageScale( bPlayer )) );
			return true;
		}

		return false;
	}

	bool HandleFlameDamage( kDictMem@ damageDef )
	{
		// flamethrower fires 10 projectiles per tick; only allow 1 to hit
		if ( self.GameTicks() == flameTick )
			return false;

		float f;
		bool bRet = false;

		// take direct damage
		if ( damageDef.GetFloat( "BurnDamage", f ) )
		{
			IncBurnAccumulator( f );
			flameTick = self.GameTicks();
			bRet = true;
		}

		// set on fire, unless in water or shielded (campaigner)
		if ( self.GetWaterLevel() <= WLT_OVER && self.ImpactType() != IT_FORCEFIELD
		  && damageDef.GetFloat( "BurnFactor", f ) )
		{
			burnFactor = Math::Min( burnFactor + f * GAME_DELTA_TIME, 1.0f );
			burnSmokeFactor = burnFactor;
			if ( burnFactor >= 0.125f && PoisonDPS <= 0 )
				self.RunFxEvent( "Ablaze"+ int( 8.0f * burnFactor ) );

			flameTick = self.GameTicks();
			bRet = true;
		}

		return bRet;
	}

	void IncBurnAccumulator( float dam )
	{
		// for now, assume all burn damage is from player
		// because to do otherwise would require tracking who set us on fire or stunned us
		// which isn't worth dealing with because, for now, all burn damage does come from the player
		burnAccumulator += dam * DifficultyDamageScale() * ( 1 + BonusDamageScale(true) );
	}

	void HandleMomentumTransfer( kDictMem@ damageDef, int damage )
	{
		// don't knock stationary enemies around, or they'll just keep getting knocked further and further back with no sign of retaliation
		// bosses and unconscious enemies are also immune
		if ( self.Flags() & AF_STATIONARY != 0 || bSedated || IsBoss() ) return;

		float momentum = GetFloat( damageDef, "MomentumTransfer" );
		if ( momentum <= 0 ) return;

		bool bExplode = GetBool( damageDef, "bExplode" );
		if ( bExplode )
		{
			// don't add momentum if already being blown away by explosive death
			if ( AIFlags() & AIF_BLOWNAWAY != 0 )
				momentum = 0;
			else
			{
				int max = int( GetInt( damageDef, "damage" ) * DifficultyDamageScale() );
				momentum *= Math::Min( float( damage ) / max, 1.0f );
			}
		}
		// allow knockback to be range limited
		// we could use invisible projectiles with limited range, but lifeTime gives us only very coarse control over range, and adjusting proj speed can cause knockback to apply out of sync with damage
		// that desync might not be very noticable, but in any case this is still easier to tweak precisely
		float r = GetFloat( damageDef, "RangeLimit" );
		if ( r > 0 )
		{
			kVec3 dif = Player.Actor().Origin() - self.Origin();
			float dist = dif.Unit() - self.Radius() - Player.Actor().Radius();
			if ( dist <= r )
				TransferMomentum( momentum, bExplode );
		}
		else
			TransferMomentum( momentum, bExplode );
	}

	// instigator is self, which gives us no useful info on projectile position or trajectory
	// so instead, we fake it by moving in the direction the player is facing
	void TransferMomentum( float momentumTransfer, bool bExplode )
	{
		kVec3 dir;
		if ( bExplode )
		{
			dir = self.Origin() - Player.Actor().Origin();
			dir.z = 0;
			dir.Normalize();
			if ( self.OnGround() && self.Velocity().z <= 0 )
				dir.z = 0.2f;
		}
		else
		{
			dir = kVec3(0,1,0) * Player.Actor().Rotation();
			dir.z = 0.1f;
		}
		self.Velocity() += dir * momentumTransfer * 0.2f;
	}

	void HandleAlienFreeze( kDictMem@ damDef )
	{
		if ( IsBoss() || !GetBool( damDef, "bAlienFreeze" ) ) return;
		AlienFreezeTimes.insertLast( 0 );
		AlienFreezeLocs.insertLast( self.Origin() );
	}

	void HandleFlareDamage( kDictMem@ damageDef )
	{
		if ( !GetBool( damageDef, "bFlare" ) ) return;
		kActor@ flare = Spawn( "StuckFlare", CModel.InterceptVector(), 0, self.SectorIndex() );
		StuckFlare@ SO = cast<StuckFlare@>( ActorScript(flare) );
		if ( SO !is null )
			SO.CollisionCommon( self, CModel.InterceptVector(), CModel.ContactNormal(), CModel.ClipResult() );
	}

	void HandleArrowDamage( kDictMem@ damageDef )
	{
		if ( GetInt( damageDef, "StickArrow" ) != 1 ) return;
		StickArrowToActor( self );
	}

	void HandleStunDamage( kDictMem@ damageDef )
	{
		float stun = GetFloat( damageDef, "StunTime" );
		if ( stun <= 0 ) return;

		float power = GetFloat( damageDef, "StunPower" );
		stun /= Math::Pow( 2, EnemyTier() - 2*power );

		StunTime += stun;
		float max = IsBoss() ? 7.5f : 15;
		if ( StunTime > max )
		{
			StunOverflow += StunTime - max;
			StunTime = max;
		}
		StunYaw = self.Yaw();
	}

	// this actor's difficulty level, as it pertains to how the game will scale its damage taken
	int DamageDifficulty()
	{
		return self.CastToAI() !is null  ?  self.DifficultyMode()  :  DIFFICULTY_NORMAL;
	}

	float DifficultyDamageScale()
	{
		switch ( DamageDifficulty() )
		{
			case DIFFICULTY_EASY:      return 1.4f;
			case DIFFICULTY_HARD:
			case DIFFICULTY_HARDCORE:  return 0.7f;
		}
		return 1.0f;
	}
};
