Portable Half-Life SDK. GoldSource and Xash3D. Crossplatform.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3486 lines
100 KiB

7 years ago
/***
*
9 years ago
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
7 years ago
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
/*
===== monsters.cpp ========================================================
Monster-related utility code
*/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "nodes.h"
#include "monsters.h"
#include "animation.h"
#include "saverestore.h"
#include "weapons.h"
#include "scripted.h"
#include "squadmonster.h"
#include "decals.h"
#include "soundent.h"
#include "gamerules.h"
#include "game.h"
7 years ago
#define MONSTER_CUT_CORNER_DIST 8 // 8 means the monster's bounding box is contained without the box of the node in WC
8 years ago
Vector VecBModelOrigin( entvars_t *pevBModel );
7 years ago
extern DLL_GLOBAL BOOL g_fDrawLines;
extern DLL_GLOBAL short g_sModelIndexLaser;// holds the index for the laser beam
extern DLL_GLOBAL short g_sModelIndexLaserDot;// holds the index for the laser beam dot
extern CGraph WorldGraph;// the world node graph
// Global Savedata for monster
// UNDONE: Save schedule data? Can this be done? We may
// lose our enemy pointer or other data (goal ent, target, etc)
// that make the current schedule invalid, perhaps it's best
// to just pick a new one when we start up again.
8 years ago
TYPEDESCRIPTION CBaseMonster::m_SaveData[] =
7 years ago
{
DEFINE_FIELD( CBaseMonster, m_hEnemy, FIELD_EHANDLE ),
DEFINE_FIELD( CBaseMonster, m_hTargetEnt, FIELD_EHANDLE ),
DEFINE_ARRAY( CBaseMonster, m_hOldEnemy, FIELD_EHANDLE, MAX_OLD_ENEMIES ),
DEFINE_ARRAY( CBaseMonster, m_vecOldEnemy, FIELD_POSITION_VECTOR, MAX_OLD_ENEMIES ),
DEFINE_FIELD( CBaseMonster, m_iClass, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_iPlayerReact, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_flFieldOfView, FIELD_FLOAT ),
DEFINE_FIELD( CBaseMonster, m_flWaitFinished, FIELD_TIME ),
DEFINE_FIELD( CBaseMonster, m_flMoveWaitFinished, FIELD_TIME ),
DEFINE_FIELD( CBaseMonster, m_Activity, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_IdealActivity, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_LastHitGroup, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_MonsterState, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_IdealMonsterState, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_iTaskStatus, FIELD_INTEGER ),
//Schedule_t *m_pSchedule;
DEFINE_FIELD( CBaseMonster, m_iScheduleIndex, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_afConditions, FIELD_INTEGER ),
//WayPoint_t m_Route[ ROUTE_SIZE ];
//DEFINE_FIELD( CBaseMonster, m_movementGoal, FIELD_INTEGER ),
//DEFINE_FIELD( CBaseMonster, m_iRouteIndex, FIELD_INTEGER ),
//DEFINE_FIELD( CBaseMonster, m_moveWaitTime, FIELD_FLOAT ),
7 years ago
DEFINE_FIELD( CBaseMonster, m_vecMoveGoal, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( CBaseMonster, m_movementActivity, FIELD_INTEGER ),
//int m_iAudibleList; // first index of a linked list of sounds that the monster can hear.
//DEFINE_FIELD( CBaseMonster, m_afSoundTypes, FIELD_INTEGER ),
7 years ago
DEFINE_FIELD( CBaseMonster, m_vecLastPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( CBaseMonster, m_iHintNode, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_afMemory, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_iMaxHealth, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_vecEnemyLKP, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( CBaseMonster, m_cAmmoLoaded, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_afCapability, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_flNextAttack, FIELD_TIME ),
DEFINE_FIELD( CBaseMonster, m_bitsDamageType, FIELD_INTEGER ),
DEFINE_ARRAY( CBaseMonster, m_rgbTimeBasedDamage, FIELD_CHARACTER, CDMG_TIMEBASED ),
DEFINE_FIELD( CBaseMonster, m_bloodColor, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_failSchedule, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_flHungryTime, FIELD_TIME ),
DEFINE_FIELD( CBaseMonster, m_flDistTooFar, FIELD_FLOAT ),
DEFINE_FIELD( CBaseMonster, m_flDistLook, FIELD_FLOAT ),
DEFINE_FIELD( CBaseMonster, m_iTriggerCondition, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_iszTriggerTarget, FIELD_STRING ),
DEFINE_FIELD( CBaseMonster, m_HackedGunPos, FIELD_VECTOR ),
DEFINE_FIELD( CBaseMonster, m_scriptState, FIELD_INTEGER ),
DEFINE_FIELD( CBaseMonster, m_pCine, FIELD_CLASSPTR ),
};
//IMPLEMENT_SAVERESTORE( CBaseMonster, CBaseToggle )
7 years ago
int CBaseMonster::Save( CSave &save )
{
8 years ago
if( !CBaseToggle::Save( save ) )
7 years ago
return 0;
if ( pev->targetname )
return save.WriteFields( STRING(pev->targetname), "CBaseMonster", this, m_SaveData, ARRAYSIZE(m_SaveData) );
else
return save.WriteFields( STRING(pev->classname), "CBaseMonster", this, m_SaveData, ARRAYSIZE(m_SaveData) );
}
int CBaseMonster::Restore( CRestore &restore )
{
8 years ago
if( !CBaseToggle::Restore( restore ) )
7 years ago
return 0;
8 years ago
int status = restore.ReadFields( "CBaseMonster", this, m_SaveData, ARRAYSIZE( m_SaveData ) );
7 years ago
// We don't save/restore routes yet
RouteClear();
// We don't save/restore schedules yet
m_pSchedule = NULL;
m_iTaskStatus = TASKSTATUS_NEW;
8 years ago
7 years ago
// Reset animation
m_Activity = ACT_RESET;
// If we don't have an enemy, clear conditions like see enemy, etc.
if( m_hEnemy == 0 )
7 years ago
m_afConditions = 0;
return status;
}
//=========================================================
// Eat - makes a monster full for a little while.
//=========================================================
8 years ago
void CBaseMonster::Eat( float flFullDuration )
7 years ago
{
m_flHungryTime = gpGlobals->time + flFullDuration;
}
//=========================================================
// FShouldEat - returns true if a monster is hungry.
//=========================================================
8 years ago
BOOL CBaseMonster::FShouldEat( void )
7 years ago
{
8 years ago
if( m_flHungryTime > gpGlobals->time )
7 years ago
{
return FALSE;
}
return TRUE;
}
//=========================================================
// BarnacleVictimBitten - called
// by Barnacle victims when the barnacle pulls their head
// into its mouth
//=========================================================
8 years ago
void CBaseMonster::BarnacleVictimBitten( entvars_t *pevBarnacle )
7 years ago
{
Schedule_t *pNewSchedule;
pNewSchedule = GetScheduleOfType( SCHED_BARNACLE_VICTIM_CHOMP );
8 years ago
if( pNewSchedule )
7 years ago
{
ChangeSchedule( pNewSchedule );
}
}
//=========================================================
// BarnacleVictimReleased - called by barnacle victims when
// the host barnacle is killed.
//=========================================================
8 years ago
void CBaseMonster::BarnacleVictimReleased( void )
7 years ago
{
m_IdealMonsterState = MONSTERSTATE_IDLE;
pev->velocity = g_vecZero;
pev->movetype = MOVETYPE_STEP;
}
//=========================================================
// Listen - monsters dig through the active sound list for
// any sounds that may interest them. (smells, too!)
//=========================================================
8 years ago
void CBaseMonster::Listen( void )
7 years ago
{
8 years ago
int iSound;
int iMySounds;
7 years ago
float hearingSensitivity;
CSound *pCurrentSound;
m_iAudibleList = SOUNDLIST_EMPTY;
8 years ago
ClearConditions( bits_COND_HEAR_SOUND | bits_COND_SMELL | bits_COND_SMELL_FOOD );
7 years ago
m_afSoundTypes = 0;
iMySounds = ISoundMask();
8 years ago
if( m_pSchedule )
7 years ago
{
//!!!WATCH THIS SPOT IF YOU ARE HAVING SOUND RELATED BUGS!
// Make sure your schedule AND personal sound masks agree!
iMySounds &= m_pSchedule->iSoundMask;
}
iSound = CSoundEnt::ActiveList();
// UNDONE: Clear these here?
ClearConditions( bits_COND_HEAR_SOUND | bits_COND_SMELL_FOOD | bits_COND_SMELL );
8 years ago
hearingSensitivity = HearingSensitivity();
7 years ago
8 years ago
while( iSound != SOUNDLIST_EMPTY )
7 years ago
{
pCurrentSound = CSoundEnt::SoundPointerForIndex( iSound );
8 years ago
if( pCurrentSound &&
( pCurrentSound->m_iType & iMySounds ) &&
( pCurrentSound->m_vecOrigin - EarPosition() ).Length() <= pCurrentSound->m_iVolume * hearingSensitivity )
7 years ago
8 years ago
//if( ( g_pSoundEnt->m_SoundPool[iSound].m_iType & iMySounds ) && ( g_pSoundEnt->m_SoundPool[iSound].m_vecOrigin - EarPosition()).Length () <= g_pSoundEnt->m_SoundPool[iSound].m_iVolume * hearingSensitivity )
7 years ago
{
// the monster cares about this sound, and it's close enough to hear.
8 years ago
//g_pSoundEnt->m_SoundPool[iSound].m_iNextAudible = m_iAudibleList;
7 years ago
pCurrentSound->m_iNextAudible = m_iAudibleList;
8 years ago
if( pCurrentSound->FIsSound() )
7 years ago
{
// this is an audible sound.
SetConditions( bits_COND_HEAR_SOUND );
}
else
{
// if not a sound, must be a smell - determine if it's just a scent, or if it's a food scent
8 years ago
//if( g_pSoundEnt->m_SoundPool[iSound].m_iType & ( bits_SOUND_MEAT | bits_SOUND_CARCASS ) )
if( pCurrentSound->m_iType & ( bits_SOUND_MEAT | bits_SOUND_CARCASS ) )
7 years ago
{
// the detected scent is a food item, so set both conditions.
// !!!BUGBUG - maybe a virtual function to determine whether or not the scent is food?
SetConditions( bits_COND_SMELL_FOOD );
SetConditions( bits_COND_SMELL );
}
else
{
// just a normal scent.
SetConditions( bits_COND_SMELL );
}
}
8 years ago
//m_afSoundTypes |= g_pSoundEnt->m_SoundPool[iSound].m_iType;
7 years ago
m_afSoundTypes |= pCurrentSound->m_iType;
m_iAudibleList = iSound;
}
8 years ago
//iSound = g_pSoundEnt->m_SoundPool[iSound].m_iNext;
if( pCurrentSound )
iSound = pCurrentSound->m_iNext;
7 years ago
}
}
//=========================================================
// FLSoundVolume - subtracts the volume of the given sound
// from the distance the sound source is from the caller,
// and returns that value, which is considered to be the 'local'
// volume of the sound.
//=========================================================
8 years ago
float CBaseMonster::FLSoundVolume( CSound *pSound )
7 years ago
{
return ( pSound->m_iVolume - ( ( pSound->m_vecOrigin - pev->origin ).Length() ) );
}
//=========================================================
// FValidateHintType - tells use whether or not the monster cares
// about the type of Hint Node given
//=========================================================
8 years ago
BOOL CBaseMonster::FValidateHintType( short sHint )
7 years ago
{
return FALSE;
}
//=========================================================
// Look - Base class monster function to find enemies or
// food by sight. iDistance is distance ( in units ) that the
// monster can see.
//
// Sets the sight bits of the m_afConditions mask to indicate
// which types of entities were sighted.
// Function also sets the Looker's m_pLink
// to the head of a link list that contains all visible ents.
// (linked via each ent's m_pLink field)
//
//=========================================================
8 years ago
void CBaseMonster::Look( int iDistance )
7 years ago
{
8 years ago
int iSighted = 0;
7 years ago
// DON'T let visibility information from last frame sit around!
8 years ago
ClearConditions( bits_COND_SEE_HATE | bits_COND_SEE_DISLIKE | bits_COND_SEE_ENEMY | bits_COND_SEE_FEAR | bits_COND_SEE_NEMESIS | bits_COND_SEE_CLIENT );
7 years ago
m_pLink = NULL;
8 years ago
CBaseEntity *pSightEnt = NULL;// the current visible entity that we're dealing with
7 years ago
// See no evil if prisoner is set
8 years ago
if( !FBitSet( pev->spawnflags, SF_MONSTER_PRISONER ) )
7 years ago
{
CBaseEntity *pList[100];
Vector delta = Vector( iDistance, iDistance, iDistance );
// Find only monsters/clients in box, NOT limited to PVS
8 years ago
int count = UTIL_EntitiesInBox( pList, 100, pev->origin - delta, pev->origin + delta, FL_CLIENT | FL_MONSTER );
for( int i = 0; i < count; i++ )
7 years ago
{
pSightEnt = pList[i];
// !!!temporarily only considering other monsters and clients, don't see prisoners
8 years ago
if( pSightEnt != this &&
!FBitSet( pSightEnt->pev->spawnflags, SF_MONSTER_PRISONER ) &&
7 years ago
pSightEnt->pev->health > 0 )
{
// the looker will want to consider this entity
// don't check anything else about an entity that can't be seen, or an entity that you don't care about.
8 years ago
if( IRelationship( pSightEnt ) != R_NO && FInViewCone( pSightEnt ) && !FBitSet( pSightEnt->pev->flags, FL_NOTARGET ) && FVisible( pSightEnt ) )
7 years ago
{
8 years ago
if( pSightEnt->IsPlayer() )
7 years ago
{
8 years ago
if( pev->spawnflags & SF_MONSTER_WAIT_TILL_SEEN )
7 years ago
{
CBaseMonster *pClient;
pClient = pSightEnt->MyMonsterPointer();
// don't link this client in the list if the monster is wait till seen and the player isn't facing the monster
if ( pSightEnt && !pClient->FInViewCone( this ) )
{
// we're not in the player's view cone.
continue;
}
else
{
// player sees us, become normal now.
pev->spawnflags &= ~SF_MONSTER_WAIT_TILL_SEEN;
}
}
// if we see a client, remember that (mostly for scripted AI)
iSighted |= bits_COND_SEE_CLIENT;
}
pSightEnt->m_pLink = m_pLink;
m_pLink = pSightEnt;
8 years ago
if( pSightEnt == m_hEnemy )
7 years ago
{
// we know this ent is visible, so if it also happens to be our enemy, store that now.
iSighted |= bits_COND_SEE_ENEMY;
}
// don't add the Enemy's relationship to the conditions. We only want to worry about conditions when
// we see monsters other than the Enemy.
8 years ago
switch( IRelationship( pSightEnt ) )
7 years ago
{
8 years ago
case R_NM:
7 years ago
iSighted |= bits_COND_SEE_NEMESIS;
break;
8 years ago
case R_HT:
7 years ago
iSighted |= bits_COND_SEE_HATE;
break;
8 years ago
case R_DL:
7 years ago
iSighted |= bits_COND_SEE_DISLIKE;
break;
8 years ago
case R_FR:
7 years ago
iSighted |= bits_COND_SEE_FEAR;
break;
8 years ago
case R_AL:
7 years ago
break;
default:
8 years ago
ALERT( at_aiconsole, "%s can't assess %s\n", STRING( pev->classname ), STRING( pSightEnt->pev->classname ) );
7 years ago
break;
}
}
}
}
}
7 years ago
SetConditions( iSighted );
}
//=========================================================
// ISoundMask - returns a bit mask indicating which types
// of sounds this monster regards. In the base class implementation,
// monsters care about all sounds, but no scents.
//=========================================================
8 years ago
int CBaseMonster::ISoundMask( void )
7 years ago
{
8 years ago
return bits_SOUND_WORLD |
bits_SOUND_COMBAT |
bits_SOUND_PLAYER;
7 years ago
}
//=========================================================
// PBestSound - returns a pointer to the sound the monster
// should react to. Right now responds only to nearest sound.
//=========================================================
8 years ago
CSound *CBaseMonster::PBestSound( void )
7 years ago
{
int iThisSound;
8 years ago
int iBestSound = -1;
7 years ago
float flBestDist = 8192;// so first nearby sound will become best so far.
float flDist;
CSound *pSound;
iThisSound = m_iAudibleList;
8 years ago
if( iThisSound == SOUNDLIST_EMPTY )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "ERROR! monster %s has no audible sounds!\n", STRING( pev->classname ) );
7 years ago
#if _DEBUG
ALERT( at_error, "NULL Return from PBestSound\n" );
#endif
return NULL;
}
8 years ago
while( iThisSound != SOUNDLIST_EMPTY )
7 years ago
{
pSound = CSoundEnt::SoundPointerForIndex( iThisSound );
if( pSound )
7 years ago
{
if( pSound->FIsSound() )
7 years ago
{
flDist = ( pSound->m_vecOrigin - EarPosition() ).Length();
if( flDist < flBestDist )
{
iBestSound = iThisSound;
flBestDist = flDist;
}
7 years ago
}
iThisSound = pSound->m_iNextAudible;
}
7 years ago
}
8 years ago
if( iBestSound >= 0 )
7 years ago
{
pSound = CSoundEnt::SoundPointerForIndex( iBestSound );
return pSound;
}
#if _DEBUG
ALERT( at_error, "NULL Return from PBestSound\n" );
#endif
return NULL;
}
//=========================================================
// PBestScent - returns a pointer to the scent the monster
// should react to. Right now responds only to nearest scent
//=========================================================
8 years ago
CSound *CBaseMonster::PBestScent( void )
{
7 years ago
int iThisScent;
8 years ago
int iBestScent = -1;
7 years ago
float flBestDist = 8192;// so first nearby smell will become best so far.
float flDist;
CSound *pSound;
iThisScent = m_iAudibleList;// smells are in the sound list.
8 years ago
if( iThisScent == SOUNDLIST_EMPTY )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "ERROR! PBestScent() has empty soundlist!\n" );
7 years ago
#if _DEBUG
ALERT( at_error, "NULL Return from PBestSound\n" );
#endif
return NULL;
}
8 years ago
while( iThisScent != SOUNDLIST_EMPTY )
7 years ago
{
pSound = CSoundEnt::SoundPointerForIndex( iThisScent );
8 years ago
if( pSound->FIsScent() )
7 years ago
{
flDist = ( pSound->m_vecOrigin - pev->origin ).Length();
8 years ago
if( flDist < flBestDist )
7 years ago
{
iBestScent = iThisScent;
flBestDist = flDist;
}
}
iThisScent = pSound->m_iNextAudible;
}
8 years ago
if( iBestScent >= 0 )
7 years ago
{
pSound = CSoundEnt::SoundPointerForIndex( iBestScent );
return pSound;
}
#if _DEBUG
ALERT( at_error, "NULL Return from PBestScent\n" );
#endif
return NULL;
}
//=========================================================
// Monster Think - calls out to core AI functions and handles this
// monster's specific animation events
//=========================================================
8 years ago
void CBaseMonster::MonsterThink( void )
7 years ago
{
SetNextThink( 0.1f );// keep monster thinking.
7 years ago
RunAI();
float flInterval = StudioFrameAdvance( ); // animate
// start or end a fidget
// This needs a better home -- switching animations over time should be encapsulated on a per-activity basis
// perhaps MaintainActivity() or a ShiftAnimationOverTime() or something.
8 years ago
if( m_MonsterState != MONSTERSTATE_SCRIPT && m_MonsterState != MONSTERSTATE_DEAD && m_Activity == ACT_IDLE && m_fSequenceFinished )
7 years ago
{
int iSequence;
8 years ago
if( m_fSequenceLoops )
7 years ago
{
// animation does loop, which means we're playing subtle idle. Might need to
// fidget.
8 years ago
iSequence = LookupActivity( m_Activity );
7 years ago
}
else
{
// animation that just ended doesn't loop! That means we just finished a fidget
// and should return to our heaviest weighted idle (the subtle one)
8 years ago
iSequence = LookupActivityHeaviest( m_Activity );
7 years ago
}
8 years ago
if( iSequence != ACTIVITY_NOT_AVAILABLE )
7 years ago
{
pev->sequence = iSequence; // Set to new anim (if it's there)
8 years ago
ResetSequenceInfo();
7 years ago
}
}
DispatchAnimEvents( flInterval );
8 years ago
if( !MovementIsComplete() )
7 years ago
{
Move( flInterval );
}
#if _DEBUG
else
{
8 years ago
if( !TaskIsRunning() && !TaskIsComplete() )
7 years ago
ALERT( at_error, "Schedule stalled!!\n" );
}
#endif
}
//=========================================================
// CBaseMonster - USE - will make a monster angry at whomever
// activated it.
//=========================================================
8 years ago
void CBaseMonster::MonsterUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
7 years ago
{
m_IdealMonsterState = MONSTERSTATE_ALERT;
}
//=========================================================
// Ignore conditions - before a set of conditions is allowed
// to interrupt a monster's schedule, this function removes
// conditions that we have flagged to interrupt the current
// schedule, but may not want to interrupt the schedule every
// time. (Pain, for instance)
//=========================================================
8 years ago
int CBaseMonster::IgnoreConditions( void )
7 years ago
{
int iIgnoreConditions = 0;
8 years ago
if( !FShouldEat() )
7 years ago
{
// not hungry? Ignore food smell.
iIgnoreConditions |= bits_COND_SMELL_FOOD;
}
8 years ago
if( m_MonsterState == MONSTERSTATE_SCRIPT && m_pCine )
7 years ago
iIgnoreConditions |= m_pCine->IgnoreConditions();
return iIgnoreConditions;
}
//=========================================================
// RouteClear - zeroes out the monster's route array and goal
//=========================================================
8 years ago
void CBaseMonster::RouteClear( void )
7 years ago
{
RouteNew();
m_movementGoal = MOVEGOAL_NONE;
m_movementActivity = ACT_IDLE;
Forget( bits_MEMORY_MOVE_FAILED );
}
//=========================================================
// Route New - clears out a route to be changed, but keeps
// goal intact.
//=========================================================
8 years ago
void CBaseMonster::RouteNew( void )
7 years ago
{
8 years ago
m_Route[0].iType = 0;
m_iRouteIndex = 0;
7 years ago
}
//=========================================================
// FRouteClear - returns TRUE if the Route is cleared out
// ( invalid )
//=========================================================
8 years ago
BOOL CBaseMonster::FRouteClear( void )
7 years ago
{
8 years ago
if( m_Route[m_iRouteIndex].iType == 0 || m_movementGoal == MOVEGOAL_NONE )
7 years ago
return TRUE;
return FALSE;
}
//=========================================================
// FRefreshRoute - after calculating a path to the monster's
// target, this function copies as many waypoints as possible
// from that path to the monster's Route array
//=========================================================
8 years ago
BOOL CBaseMonster::FRefreshRoute( void )
7 years ago
{
CBaseEntity *pPathCorner;
8 years ago
int i;
7 years ago
BOOL returnCode;
RouteNew();
returnCode = FALSE;
switch( m_movementGoal )
{
case MOVEGOAL_PATHCORNER:
{
// monster is on a path_corner loop
pPathCorner = m_pGoalEnt;
i = 0;
8 years ago
while( pPathCorner && i < ROUTE_SIZE )
7 years ago
{
8 years ago
m_Route[i].iType = bits_MF_TO_PATHCORNER;
m_Route[i].vecLocation = pPathCorner->pev->origin;
7 years ago
pPathCorner = pPathCorner->GetNextTarget();
// Last path_corner in list?
8 years ago
if( !pPathCorner )
7 years ago
m_Route[i].iType |= bits_MF_IS_GOAL;
i++;
}
}
returnCode = TRUE;
break;
case MOVEGOAL_ENEMY:
returnCode = BuildRoute( m_vecEnemyLKP, bits_MF_TO_ENEMY, m_hEnemy );
break;
case MOVEGOAL_LOCATION:
returnCode = BuildRoute( m_vecMoveGoal, bits_MF_TO_LOCATION, NULL );
break;
case MOVEGOAL_TARGETENT:
if( m_hTargetEnt != 0 )
7 years ago
{
returnCode = BuildRoute( m_hTargetEnt->pev->origin, bits_MF_TO_TARGETENT, m_hTargetEnt );
}
break;
case MOVEGOAL_NODE:
returnCode = FGetNodeRoute( m_vecMoveGoal );
8 years ago
//if( returnCode )
// RouteSimplify( NULL );
7 years ago
break;
}
return returnCode;
}
BOOL CBaseMonster::MoveToEnemy( Activity movementAct, float waitTime )
{
m_movementActivity = movementAct;
m_moveWaitTime = waitTime;
8 years ago
7 years ago
m_movementGoal = MOVEGOAL_ENEMY;
return FRefreshRoute();
}
BOOL CBaseMonster::MoveToLocation( Activity movementAct, float waitTime, const Vector &goal )
{
m_movementActivity = movementAct;
m_moveWaitTime = waitTime;
7 years ago
m_movementGoal = MOVEGOAL_LOCATION;
m_vecMoveGoal = goal;
return FRefreshRoute();
}
BOOL CBaseMonster::MoveToTarget( Activity movementAct, float waitTime )
{
m_movementActivity = movementAct;
m_moveWaitTime = waitTime;
7 years ago
m_movementGoal = MOVEGOAL_TARGETENT;
return FRefreshRoute();
}
BOOL CBaseMonster::MoveToNode( Activity movementAct, float waitTime, const Vector &goal )
{
m_movementActivity = movementAct;
m_moveWaitTime = waitTime;
m_movementGoal = MOVEGOAL_NODE;
m_vecMoveGoal = goal;
return FRefreshRoute();
}
#ifdef _DEBUG
void DrawRoute( entvars_t *pev, WayPoint_t *m_Route, int m_iRouteIndex, int r, int g, int b )
{
8 years ago
int i;
7 years ago
8 years ago
if( m_Route[m_iRouteIndex].iType == 0 )
7 years ago
{
ALERT( at_aiconsole, "Can't draw route!\n" );
return;
}
8 years ago
//UTIL_ParticleEffect ( m_Route[m_iRouteIndex].vecLocation, g_vecZero, 255, 25 );
7 years ago
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_BEAMPOINTS);
WRITE_COORD( pev->origin.x );
WRITE_COORD( pev->origin.y );
WRITE_COORD( pev->origin.z );
8 years ago
WRITE_COORD( m_Route[m_iRouteIndex].vecLocation.x );
WRITE_COORD( m_Route[m_iRouteIndex].vecLocation.y );
WRITE_COORD( m_Route[m_iRouteIndex].vecLocation.z );
7 years ago
WRITE_SHORT( g_sModelIndexLaser );
WRITE_BYTE( 0 ); // frame start
WRITE_BYTE( 10 ); // framerate
WRITE_BYTE( 1 ); // life
WRITE_BYTE( 16 ); // width
WRITE_BYTE( 0 ); // noise
WRITE_BYTE( r ); // r, g, b
WRITE_BYTE( g ); // r, g, b
WRITE_BYTE( b ); // r, g, b
WRITE_BYTE( 255 ); // brightness
WRITE_BYTE( 10 ); // speed
MESSAGE_END();
8 years ago
for( i = m_iRouteIndex; i < ROUTE_SIZE - 1; i++ )
7 years ago
{
8 years ago
if( ( m_Route[i].iType & bits_MF_IS_GOAL ) || ( m_Route[i + 1].iType == 0 ) )
7 years ago
break;
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_BEAMPOINTS );
8 years ago
WRITE_COORD( m_Route[i].vecLocation.x );
WRITE_COORD( m_Route[i].vecLocation.y );
WRITE_COORD( m_Route[i].vecLocation.z );
WRITE_COORD( m_Route[i + 1].vecLocation.x );
WRITE_COORD( m_Route[i + 1].vecLocation.y );
WRITE_COORD( m_Route[i + 1].vecLocation.z );
7 years ago
WRITE_SHORT( g_sModelIndexLaser );
WRITE_BYTE( 0 ); // frame start
WRITE_BYTE( 10 ); // framerate
WRITE_BYTE( 1 ); // life
WRITE_BYTE( 8 ); // width
WRITE_BYTE( 0 ); // noise
WRITE_BYTE( r ); // r, g, b
WRITE_BYTE( g ); // r, g, b
WRITE_BYTE( b ); // r, g, b
WRITE_BYTE( 255 ); // brightness
WRITE_BYTE( 10 ); // speed
MESSAGE_END();
8 years ago
//UTIL_ParticleEffect( m_Route[i].vecLocation, g_vecZero, 255, 25 );
7 years ago
}
}
#endif
int ShouldSimplify( int routeType )
{
routeType &= ~bits_MF_IS_GOAL;
8 years ago
if( ( routeType == bits_MF_TO_PATHCORNER ) || ( routeType & bits_MF_DONT_SIMPLIFY ) )
7 years ago
return FALSE;
return TRUE;
}
//=========================================================
// RouteSimplify
//
// Attempts to make the route more direct by cutting out
// unnecessary nodes & cutting corners.
//
//=========================================================
8 years ago
void CBaseMonster::RouteSimplify( CBaseEntity *pTargetEnt )
7 years ago
{
// BUGBUG: this doesn't work 100% yet
8 years ago
int i, count, outCount;
7 years ago
Vector vecStart;
8 years ago
WayPoint_t outRoute[ROUTE_SIZE * 2]; // Any points except the ends can turn into 2 points in the simplified route
7 years ago
count = 0;
8 years ago
for( i = m_iRouteIndex; i < ROUTE_SIZE; i++ )
7 years ago
{
8 years ago
if( !m_Route[i].iType )
7 years ago
break;
else
count++;
8 years ago
if( m_Route[i].iType & bits_MF_IS_GOAL )
7 years ago
break;
}
// Can't simplify a direct route!
8 years ago
if( count < 2 )
7 years ago
{
//DrawRoute( pev, m_Route, m_iRouteIndex, 0, 0, 255 );
7 years ago
return;
}
outCount = 0;
vecStart = pev->origin;
8 years ago
for( i = 0; i < count - 1; i++ )
7 years ago
{
// Don't eliminate path_corners
8 years ago
if( !ShouldSimplify( m_Route[m_iRouteIndex + i].iType ) )
7 years ago
{
8 years ago
outRoute[outCount] = m_Route[m_iRouteIndex + i];
7 years ago
outCount++;
}
8 years ago
else if( CheckLocalMove( vecStart, m_Route[m_iRouteIndex+i + 1].vecLocation, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
// Skip vert
continue;
}
else
{
Vector vecTest, vecSplit;
// Halfway between this and next
vecTest = ( m_Route[m_iRouteIndex + i + 1].vecLocation + m_Route[m_iRouteIndex + i].vecLocation ) * 0.5f;
7 years ago
// Halfway between this and previous
vecSplit = ( m_Route[m_iRouteIndex + i].vecLocation + vecStart ) * 0.5f;
7 years ago
8 years ago
int iType = ( m_Route[m_iRouteIndex + i].iType | bits_MF_TO_DETOUR ) & ~bits_MF_NOT_TO_MASK;
if( CheckLocalMove( vecStart, vecTest, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
outRoute[outCount].iType = iType;
outRoute[outCount].vecLocation = vecTest;
}
8 years ago
else if( CheckLocalMove( vecSplit, vecTest, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
outRoute[outCount].iType = iType;
outRoute[outCount].vecLocation = vecSplit;
outRoute[outCount+1].iType = iType;
outRoute[outCount+1].vecLocation = vecTest;
outCount++; // Adding an extra point
}
else
{
8 years ago
outRoute[outCount] = m_Route[m_iRouteIndex + i];
7 years ago
}
}
// Get last point
8 years ago
vecStart = outRoute[outCount].vecLocation;
7 years ago
outCount++;
}
ASSERT( i < count );
8 years ago
outRoute[outCount] = m_Route[m_iRouteIndex + i];
7 years ago
outCount++;
7 years ago
// Terminate
outRoute[outCount].iType = 0;
8 years ago
ASSERT( outCount < ( ROUTE_SIZE * 2 ) );
7 years ago
// Copy the simplified route, disable for testing
7 years ago
m_iRouteIndex = 0;
8 years ago
for( i = 0; i < ROUTE_SIZE && i < outCount; i++ )
7 years ago
{
m_Route[i] = outRoute[i];
}
// Terminate route
8 years ago
if( i < ROUTE_SIZE )
7 years ago
m_Route[i].iType = 0;
// Debug, test movement code
#if 0
8 years ago
// if( CVAR_GET_FLOAT( "simplify" ) != 0 )
7 years ago
DrawRoute( pev, outRoute, 0, 255, 0, 0 );
// else
DrawRoute( pev, m_Route, m_iRouteIndex, 0, 255, 0 );
#endif
}
//=========================================================
// FBecomeProne - tries to send a monster into PRONE state.
// right now only used when a barnacle snatches someone, so
// may have some special case stuff for that.
//=========================================================
8 years ago
BOOL CBaseMonster::FBecomeProne( void )
7 years ago
{
8 years ago
if( FBitSet( pev->flags, FL_ONGROUND ) )
7 years ago
{
pev->flags -= FL_ONGROUND;
}
m_IdealMonsterState = MONSTERSTATE_PRONE;
return TRUE;
}
//=========================================================
// CheckRangeAttack1
//=========================================================
8 years ago
BOOL CBaseMonster::CheckRangeAttack1( float flDot, float flDist )
7 years ago
{
if( flDist > 64.0f && flDist <= 784.0f && flDot >= 0.5f )
7 years ago
{
return TRUE;
}
return FALSE;
}
//=========================================================
// CheckRangeAttack2
//=========================================================
8 years ago
BOOL CBaseMonster::CheckRangeAttack2( float flDot, float flDist )
7 years ago
{
if( flDist > 64.0f && flDist <= 512.0f && flDot >= 0.5f )
7 years ago
{
return TRUE;
}
return FALSE;
}
//=========================================================
// CheckMeleeAttack1
//=========================================================
8 years ago
BOOL CBaseMonster::CheckMeleeAttack1( float flDot, float flDist )
7 years ago
{
// Decent fix to keep folks from kicking/punching hornets and snarks is to check the onground flag(sjb)
if( flDist <= 64.0f && flDot >= 0.7f && m_hEnemy != 0 && FBitSet( m_hEnemy->pev->flags, FL_ONGROUND ) )
7 years ago
{
return TRUE;
}
return FALSE;
}
//=========================================================
// CheckMeleeAttack2
//=========================================================
8 years ago
BOOL CBaseMonster::CheckMeleeAttack2( float flDot, float flDist )
7 years ago
{
if( flDist <= 64.0f && flDot >= 0.7f )
7 years ago
{
return TRUE;
}
return FALSE;
}
//=========================================================
// CheckAttacks - sets all of the bits for attacks that the
// monster is capable of carrying out on the passed entity.
//=========================================================
8 years ago
void CBaseMonster::CheckAttacks( CBaseEntity *pTarget, float flDist )
7 years ago
{
8 years ago
Vector2D vec2LOS;
float flDot;
7 years ago
8 years ago
UTIL_MakeVectors( pev->angles );
7 years ago
vec2LOS = ( pTarget->pev->origin - pev->origin ).Make2D();
vec2LOS = vec2LOS.Normalize();
8 years ago
flDot = DotProduct( vec2LOS, gpGlobals->v_forward.Make2D() );
7 years ago
// we know the enemy is in front now. We'll find which attacks the monster is capable of by
// checking for corresponding Activities in the model file, then do the simple checks to validate
// those attack types.
7 years ago
// Clear all attack conditions
ClearConditions( bits_COND_CAN_RANGE_ATTACK1 | bits_COND_CAN_RANGE_ATTACK2 | bits_COND_CAN_MELEE_ATTACK1 |bits_COND_CAN_MELEE_ATTACK2 );
8 years ago
if( m_afCapability & bits_CAP_RANGE_ATTACK1 )
7 years ago
{
8 years ago
if( CheckRangeAttack1( flDot, flDist ) )
7 years ago
SetConditions( bits_COND_CAN_RANGE_ATTACK1 );
}
8 years ago
if( m_afCapability & bits_CAP_RANGE_ATTACK2 )
7 years ago
{
8 years ago
if( CheckRangeAttack2( flDot, flDist ) )
7 years ago
SetConditions( bits_COND_CAN_RANGE_ATTACK2 );
}
8 years ago
if( m_afCapability & bits_CAP_MELEE_ATTACK1 )
7 years ago
{
8 years ago
if( CheckMeleeAttack1( flDot, flDist ) )
7 years ago
SetConditions( bits_COND_CAN_MELEE_ATTACK1 );
}
8 years ago
if( m_afCapability & bits_CAP_MELEE_ATTACK2 )
7 years ago
{
8 years ago
if( CheckMeleeAttack2( flDot, flDist ) )
7 years ago
SetConditions( bits_COND_CAN_MELEE_ATTACK2 );
}
}
//=========================================================
// CanCheckAttacks - prequalifies a monster to do more fine
// checking of potential attacks.
//=========================================================
8 years ago
BOOL CBaseMonster::FCanCheckAttacks( void )
7 years ago
{
8 years ago
if( HasConditions( bits_COND_SEE_ENEMY ) && !HasConditions( bits_COND_ENEMY_TOOFAR ) )
7 years ago
{
return TRUE;
}
return FALSE;
}
//=========================================================
// CheckEnemy - part of the Condition collection process,
// gets and stores data and conditions pertaining to a monster's
// enemy. Returns TRUE if Enemy LKP was updated.
//=========================================================
8 years ago
int CBaseMonster::CheckEnemy( CBaseEntity *pEnemy )
7 years ago
{
float flDistToEnemy;
8 years ago
int iUpdatedLKP;// set this to TRUE if you update the EnemyLKP in this function.
7 years ago
iUpdatedLKP = FALSE;
8 years ago
ClearConditions( bits_COND_ENEMY_FACING_ME );
8 years ago
if( !FVisible( pEnemy ) )
7 years ago
{
8 years ago
ASSERT( !HasConditions( bits_COND_SEE_ENEMY ) );
7 years ago
SetConditions( bits_COND_ENEMY_OCCLUDED );
}
else
ClearConditions( bits_COND_ENEMY_OCCLUDED );
8 years ago
if( !pEnemy->IsAlive() )
7 years ago
{
8 years ago
SetConditions( bits_COND_ENEMY_DEAD );
7 years ago
ClearConditions( bits_COND_SEE_ENEMY | bits_COND_ENEMY_OCCLUDED );
return FALSE;
}
Vector vecEnemyPos = pEnemy->pev->origin;
7 years ago
// distance to enemy's origin
flDistToEnemy = ( vecEnemyPos - pev->origin ).Length();
vecEnemyPos.z += pEnemy->pev->size.z * 0.5f;
7 years ago
// distance to enemy's head
8 years ago
float flDistToEnemy2 = ( vecEnemyPos - pev->origin ).Length();
if( flDistToEnemy2 < flDistToEnemy )
7 years ago
flDistToEnemy = flDistToEnemy2;
else
{
// distance to enemy's feet
vecEnemyPos.z -= pEnemy->pev->size.z;
8 years ago
flDistToEnemy2 = ( vecEnemyPos - pev->origin ).Length();
8 years ago
if( flDistToEnemy2 < flDistToEnemy )
7 years ago
flDistToEnemy = flDistToEnemy2;
}
8 years ago
if( HasConditions( bits_COND_SEE_ENEMY ) )
7 years ago
{
CBaseMonster *pEnemyMonster;
iUpdatedLKP = TRUE;
m_vecEnemyLKP = pEnemy->pev->origin;
pEnemyMonster = pEnemy->MyMonsterPointer();
8 years ago
if( pEnemyMonster )
7 years ago
{
8 years ago
if( pEnemyMonster->FInViewCone( this ) )
7 years ago
{
8 years ago
SetConditions( bits_COND_ENEMY_FACING_ME );
7 years ago
}
else
ClearConditions( bits_COND_ENEMY_FACING_ME );
}
8 years ago
if( pEnemy->pev->velocity != Vector( 0, 0, 0 ) )
7 years ago
{
// trail the enemy a bit
m_vecEnemyLKP = m_vecEnemyLKP - pEnemy->pev->velocity * RANDOM_FLOAT( -0.05f, 0.0f );
7 years ago
}
else
{
// UNDONE: use pev->oldorigin?
}
}
8 years ago
else if( !HasConditions( bits_COND_ENEMY_OCCLUDED | bits_COND_SEE_ENEMY ) && ( flDistToEnemy <= 256 ) )
7 years ago
{
// if the enemy is not occluded, and unseen, that means it is behind or beside the monster.
// if the enemy is near enough the monster, we go ahead and let the monster know where the
// enemy is.
iUpdatedLKP = TRUE;
m_vecEnemyLKP = pEnemy->pev->origin;
}
8 years ago
if( flDistToEnemy >= m_flDistTooFar )
7 years ago
{
// enemy is very far away from monster
SetConditions( bits_COND_ENEMY_TOOFAR );
}
else
ClearConditions( bits_COND_ENEMY_TOOFAR );
8 years ago
if( FCanCheckAttacks() )
7 years ago
{
8 years ago
CheckAttacks( m_hEnemy, flDistToEnemy );
7 years ago
}
8 years ago
if( m_movementGoal == MOVEGOAL_ENEMY )
7 years ago
{
8 years ago
for( int i = m_iRouteIndex; i < ROUTE_SIZE; i++ )
7 years ago
{
8 years ago
if( m_Route[i].iType == ( bits_MF_IS_GOAL | bits_MF_TO_ENEMY ) )
7 years ago
{
// UNDONE: Should we allow monsters to override this distance (80?)
if( ( m_Route[i].vecLocation - m_vecEnemyLKP ).Length() > 80.0f )
7 years ago
{
// Refresh
FRefreshRoute();
return iUpdatedLKP;
}
}
}
}
return iUpdatedLKP;
}
//=========================================================
// PushEnemy - remember the last few enemies, always remember the player
//=========================================================
8 years ago
void CBaseMonster::PushEnemy( CBaseEntity *pEnemy, Vector &vecLastKnownPos )
7 years ago
{
int i;
8 years ago
if( pEnemy == NULL )
7 years ago
return;
// UNDONE: blah, this is bad, we should use a stack but I'm too lazy to code one.
8 years ago
for( i = 0; i < MAX_OLD_ENEMIES; i++ )
7 years ago
{
8 years ago
if( m_hOldEnemy[i] == pEnemy )
7 years ago
return;
if( m_hOldEnemy[i] == 0 ) // someone died, reuse their slot
7 years ago
break;
}
8 years ago
if( i >= MAX_OLD_ENEMIES )
7 years ago
return;
m_hOldEnemy[i] = pEnemy;
m_vecOldEnemy[i] = vecLastKnownPos;
}
//=========================================================
// PopEnemy - try remembering the last few enemies
//=========================================================
8 years ago
BOOL CBaseMonster::PopEnemy()
7 years ago
{
// UNDONE: blah, this is bad, we should use a stack but I'm too lazy to code one.
8 years ago
for( int i = MAX_OLD_ENEMIES - 1; i >= 0; i-- )
7 years ago
{
if( m_hOldEnemy[i] != 0 )
7 years ago
{
8 years ago
if( m_hOldEnemy[i]->IsAlive()) // cheat and know when they die
7 years ago
{
m_hEnemy = m_hOldEnemy[i];
m_vecEnemyLKP = m_vecOldEnemy[i];
8 years ago
// ALERT( at_console, "remembering\n" );
7 years ago
return TRUE;
}
else
{
m_hOldEnemy[i] = NULL;
}
}
}
return FALSE;
}
//=========================================================
// SetActivity
//=========================================================
8 years ago
void CBaseMonster::SetActivity( Activity NewActivity )
7 years ago
{
8 years ago
int iSequence;
7 years ago
8 years ago
iSequence = LookupActivity( NewActivity );
7 years ago
Activity OldActivity = m_Activity;
m_Activity = NewActivity; // Go ahead and set this so it doesn't keep trying when the anim is not present
// In case someone calls this with something other than the ideal activity
m_IdealActivity = m_Activity;
7 years ago
// Set to the desired anim, or default anim if the desired is not present
8 years ago
if( iSequence > ACTIVITY_NOT_AVAILABLE )
7 years ago
{
8 years ago
if( pev->sequence != iSequence || !m_fSequenceLoops )
7 years ago
{
// don't reset frame between walk and run
if( !( OldActivity == ACT_WALK || OldActivity == ACT_RUN ) || !( NewActivity == ACT_WALK || NewActivity == ACT_RUN ) )
7 years ago
pev->frame = 0;
}
8 years ago
pev->sequence = iSequence; // Set to the reset anim (if it's there)
ResetSequenceInfo();
7 years ago
SetYawSpeed();
}
else
{
// Not available try to get default anim
8 years ago
ALERT( at_aiconsole, "%s has no sequence for act:%d\n", STRING( pev->classname ), NewActivity );
pev->sequence = 0; // Set to the reset anim (if it's there)
7 years ago
}
}
//=========================================================
// SetSequenceByName
//=========================================================
void CBaseMonster::SetSequenceByName( const char *szSequence )
7 years ago
{
8 years ago
int iSequence;
7 years ago
8 years ago
iSequence = LookupSequence( szSequence );
7 years ago
// Set to the desired anim, or default anim if the desired is not present
8 years ago
if( iSequence > ACTIVITY_NOT_AVAILABLE )
7 years ago
{
8 years ago
if( pev->sequence != iSequence || !m_fSequenceLoops )
7 years ago
{
pev->frame = 0;
}
8 years ago
pev->sequence = iSequence; // Set to the reset anim (if it's there)
ResetSequenceInfo();
7 years ago
SetYawSpeed();
}
else
{
// Not available try to get default anim
8 years ago
ALERT( at_aiconsole, "%s has no sequence named:%f\n", STRING(pev->classname), szSequence );
pev->sequence = 0; // Set to the reset anim (if it's there)
7 years ago
}
}
//=========================================================
// CheckLocalMove - returns TRUE if the caller can walk a
// straight line from its current origin to the given
// location. If so, don't use the node graph!
//
// if a valid pointer to a int is passed, the function
// will fill that int with the distance that the check
// reached before hitting something. THIS ONLY HAPPENS
// IF THE LOCAL MOVE CHECK FAILS!
//
// !!!PERFORMANCE - should we try to load balance this?
// DON"T USE SETORIGIN!
//=========================================================
#define LOCAL_STEP_SIZE 16
8 years ago
int CBaseMonster::CheckLocalMove( const Vector &vecStart, const Vector &vecEnd, CBaseEntity *pTarget, float *pflDist )
7 years ago
{
8 years ago
Vector vecStartPos;// record monster's position before trying the move
float flYaw;
float flDist;
float flStep, stepSize;
int iReturn;
7 years ago
vecStartPos = pev->origin;
8 years ago
flYaw = UTIL_VecToYaw( vecEnd - vecStart );// build a yaw that points to the goal.
7 years ago
flDist = ( vecEnd - vecStart ).Length2D();// get the distance.
iReturn = LOCALMOVE_VALID;// assume everything will be ok.
// move the monster to the start of the local move that's to be checked.
UTIL_SetOrigin( this, vecStart );// !!!BUGBUG - won't this fire triggers? - nope, SetOrigin doesn't fire
8 years ago
if( !( pev->flags & ( FL_FLY | FL_SWIM ) ) )
7 years ago
{
DROP_TO_FLOOR( ENT( pev ) );//make sure monster is on the floor!
}
//pev->origin.z = vecStartPos.z;//!!!HACKHACK
//pev->origin = vecStart;
7 years ago
/*
8 years ago
if( flDist > 1024 )
7 years ago
{
// !!!PERFORMANCE - this operation may be too CPU intensive to try checks this large.
// We don't lose much here, because a distance this great is very likely
// to have something in the way.
// since we've actually moved the monster during the check, undo the move.
pev->origin = vecStartPos;
return FALSE;
}
*/
// this loop takes single steps to the goal.
8 years ago
for( flStep = 0; flStep < flDist; flStep += LOCAL_STEP_SIZE )
7 years ago
{
stepSize = LOCAL_STEP_SIZE;
8 years ago
if( ( flStep + LOCAL_STEP_SIZE ) >= ( flDist - 1 ) )
stepSize = ( flDist - flStep ) - 1;
7 years ago
8 years ago
//UTIL_ParticleEffect( pev->origin, g_vecZero, 255, 25 );
9 years ago
8 years ago
if( !WALK_MOVE( ENT( pev ), flYaw, stepSize, WALKMOVE_CHECKONLY ) )
{
// can't take the next step, fail!
8 years ago
if( pflDist != NULL )
7 years ago
{
*pflDist = flStep;
}
8 years ago
if( pTarget && pTarget->edict() == gpGlobals->trace_ent )
7 years ago
{
// if this step hits target ent, the move is legal.
iReturn = LOCALMOVE_VALID;
break;
}
else
{
// If we're going toward an entity, and we're almost getting there, it's OK.
8 years ago
//if( pTarget && fabs( flDist - iStep ) < LOCAL_STEP_SIZE )
// fReturn = TRUE;
//else
7 years ago
iReturn = LOCALMOVE_INVALID;
break;
}
}
}
8 years ago
if( iReturn == LOCALMOVE_VALID && !( pev->flags & ( FL_FLY | FL_SWIM ) ) && ( !pTarget || ( pTarget->pev->flags & FL_ONGROUND ) ) )
7 years ago
{
// The monster can move to a spot UNDER the target, but not to it. Don't try to triangulate, go directly to the node graph.
// UNDONE: Magic # 64 -- this used to be pev->size.z but that won't work for small creatures like the headcrab
if( fabs( vecEnd.z - pev->origin.z ) > 64.0f )
7 years ago
{
iReturn = LOCALMOVE_INVALID_DONT_TRIANGULATE;
}
}
/*
// uncommenting this block will draw a line representing the nearest legal move.
8 years ago
WRITE_BYTE( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( MSG_BROADCAST, TE_SHOWLINE );
WRITE_COORD( MSG_BROADCAST, pev->origin.x );
WRITE_COORD( MSG_BROADCAST, pev->origin.y );
WRITE_COORD( MSG_BROADCAST, pev->origin.z );
WRITE_COORD( MSG_BROADCAST, vecStart.x );
WRITE_COORD( MSG_BROADCAST, vecStart.y );
WRITE_COORD( MSG_BROADCAST, vecStart.z );
7 years ago
*/
// since we've actually moved the monster during the check, undo the move.
UTIL_SetOrigin( this, vecStartPos );
return iReturn;
}
8 years ago
float CBaseMonster::OpenDoorAndWait( entvars_t *pevDoor )
7 years ago
{
float flTravelTime = 0;
8 years ago
//ALERT( at_aiconsole, "A door. " );
CBaseEntity *pcbeDoor = CBaseEntity::Instance( pevDoor );
if( pcbeDoor && !pcbeDoor->IsLockedByMaster() )
7 years ago
{
8 years ago
//ALERT( at_aiconsole, "unlocked! " );
pcbeDoor->Use( this, this, USE_ON, 0.0 );
//ALERT( at_aiconsole, "pevDoor->nextthink = %d ms\n", (int)( 1000 * pevDoor->nextthink ) );
//ALERT( at_aiconsole, "pevDoor->ltime = %d ms\n", (int)( 1000 * pevDoor->ltime ) );
//ALERT( at_aiconsole, "pev-> nextthink = %d ms\n", (int)( 1000 * pev->nextthink ) );
//ALERT( at_aiconsole, "pev->ltime = %d ms\n", (int)( 1000 * pev->ltime ) );
7 years ago
flTravelTime = pcbeDoor->m_fNextThink - pevDoor->ltime;
8 years ago
//ALERT( at_aiconsole, "Waiting %d ms\n", (int)( 1000 * flTravelTime ) );
if( pcbeDoor->pev->targetname )
7 years ago
{
CBaseEntity *pTarget = NULL;
8 years ago
for( ; ; )
7 years ago
{
pTarget = UTIL_FindEntityByTargetname( pTarget, STRING(pcbeDoor->pev->targetname));
if (!pTarget)
9 years ago
break;
7 years ago
if ( VARS( pTarget->pev ) != pcbeDoor->pev &&
FClassnameIs ( pTarget->pev, STRING(pcbeDoor->pev->classname) ) )
9 years ago
{
7 years ago
pTarget->Use(this, this, USE_ON, 0.0);
}
}
}
}
return gpGlobals->time + flTravelTime;
}
//=========================================================
// AdvanceRoute - poorly named function that advances the
// m_iRouteIndex. If it goes beyond ROUTE_SIZE, the route
// is refreshed.
//=========================================================
8 years ago
void CBaseMonster::AdvanceRoute( float distance )
7 years ago
{
8 years ago
if( m_iRouteIndex == ROUTE_SIZE - 1 )
7 years ago
{
// time to refresh the route.
8 years ago
if( !FRefreshRoute() )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "Can't Refresh Route!!\n" );
7 years ago
}
}
else
{
8 years ago
if( !( m_Route[m_iRouteIndex].iType & bits_MF_IS_GOAL ) )
7 years ago
{
// If we've just passed a path_corner, advance m_pGoalEnt
8 years ago
if( ( m_Route[m_iRouteIndex].iType & ~bits_MF_NOT_TO_MASK ) == bits_MF_TO_PATHCORNER )
7 years ago
m_pGoalEnt = m_pGoalEnt->GetNextTarget();
// IF both waypoints are nodes, then check for a link for a door and operate it.
//
8 years ago
if( ( m_Route[m_iRouteIndex].iType & bits_MF_TO_NODE ) == bits_MF_TO_NODE
&& ( m_Route[m_iRouteIndex + 1].iType & bits_MF_TO_NODE ) == bits_MF_TO_NODE )
7 years ago
{
8 years ago
//ALERT( at_aiconsole, "SVD: Two nodes. " );
7 years ago
8 years ago
int iSrcNode = WorldGraph.FindNearestNode( m_Route[m_iRouteIndex].vecLocation, this );
int iDestNode = WorldGraph.FindNearestNode( m_Route[m_iRouteIndex + 1].vecLocation, this );
7 years ago
int iLink;
8 years ago
WorldGraph.HashSearch( iSrcNode, iDestNode, iLink );
7 years ago
8 years ago
if( iLink >= 0 && WorldGraph.m_pLinkPool[iLink].m_pLinkEnt != NULL )
7 years ago
{
8 years ago
//ALERT( at_aiconsole, "A link. " );
if( WorldGraph.HandleLinkEnt( iSrcNode, WorldGraph.m_pLinkPool[iLink].m_pLinkEnt, m_afCapability, CGraph::NODEGRAPH_DYNAMIC ) )
7 years ago
{
8 years ago
//ALERT( at_aiconsole, "usable." );
7 years ago
entvars_t *pevDoor = WorldGraph.m_pLinkPool[iLink].m_pLinkEnt;
8 years ago
if( pevDoor )
7 years ago
{
m_flMoveWaitFinished = OpenDoorAndWait( pevDoor );
//ALERT( at_aiconsole, "Wating for door %.2f\n", m_flMoveWaitFinished-gpGlobals->time );
7 years ago
}
}
}
8 years ago
//ALERT( at_aiconsole, "\n" );
7 years ago
}
m_iRouteIndex++;
}
else // At goal!!!
{
if( distance < m_flGroundSpeed * 0.2f /* FIX */ )
7 years ago
{
MovementComplete();
}
}
}
}
8 years ago
int CBaseMonster::RouteClassify( int iMoveFlag )
7 years ago
{
int movementGoal;
movementGoal = MOVEGOAL_NONE;
8 years ago
if( iMoveFlag & bits_MF_TO_TARGETENT )
7 years ago
movementGoal = MOVEGOAL_TARGETENT;
8 years ago
else if( iMoveFlag & bits_MF_TO_ENEMY )
7 years ago
movementGoal = MOVEGOAL_ENEMY;
8 years ago
else if( iMoveFlag & bits_MF_TO_PATHCORNER )
7 years ago
movementGoal = MOVEGOAL_PATHCORNER;
8 years ago
else if( iMoveFlag & bits_MF_TO_NODE )
7 years ago
movementGoal = MOVEGOAL_NODE;
8 years ago
else if( iMoveFlag & bits_MF_TO_LOCATION )
7 years ago
movementGoal = MOVEGOAL_LOCATION;
return movementGoal;
}
//=========================================================
// BuildRoute
//=========================================================
8 years ago
BOOL CBaseMonster::BuildRoute( const Vector &vecGoal, int iMoveFlag, CBaseEntity *pTarget )
7 years ago
{
8 years ago
float flDist;
Vector vecApex;
int iLocalMove;
7 years ago
RouteNew();
m_movementGoal = RouteClassify( iMoveFlag );
// so we don't end up with no moveflags
8 years ago
m_Route[0].vecLocation = vecGoal;
m_Route[0].iType = iMoveFlag | bits_MF_IS_GOAL;
7 years ago
// check simple local move
7 years ago
iLocalMove = CheckLocalMove( pev->origin, vecGoal, pTarget, &flDist );
8 years ago
if( iLocalMove == LOCALMOVE_VALID )
7 years ago
{
// monster can walk straight there!
return TRUE;
}
// try to triangulate around any obstacles.
8 years ago
else if( iLocalMove != LOCALMOVE_INVALID_DONT_TRIANGULATE && FTriangulate( pev->origin, vecGoal, flDist, pTarget, &vecApex ) )
7 years ago
{
// there is a slightly more complicated path that allows the monster to reach vecGoal
8 years ago
m_Route[0].vecLocation = vecApex;
m_Route[0].iType = (iMoveFlag | bits_MF_TO_DETOUR);
7 years ago
8 years ago
m_Route[1].vecLocation = vecGoal;
m_Route[1].iType = iMoveFlag | bits_MF_IS_GOAL;
7 years ago
/*
8 years ago
WRITE_BYTE( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( MSG_BROADCAST, TE_SHOWLINE );
WRITE_COORD( MSG_BROADCAST, vecApex.x );
WRITE_COORD( MSG_BROADCAST, vecApex.y );
WRITE_COORD( MSG_BROADCAST, vecApex.z );
WRITE_COORD( MSG_BROADCAST, vecApex.x );
WRITE_COORD( MSG_BROADCAST, vecApex.y );
WRITE_COORD( MSG_BROADCAST, vecApex.z + 128 );
7 years ago
*/
RouteSimplify( pTarget );
return TRUE;
}
// last ditch, try nodes
8 years ago
if( FGetNodeRoute( vecGoal ) )
7 years ago
{
8 years ago
//ALERT( at_console, "Can get there on nodes\n" );
7 years ago
m_vecMoveGoal = vecGoal;
RouteSimplify( pTarget );
return TRUE;
}
// b0rk
return FALSE;
}
//=========================================================
// InsertWaypoint - Rebuilds the existing route so that the
// supplied vector and moveflags are the first waypoint in
// the route, and fills the rest of the route with as much
// of the pre-existing route as possible
//=========================================================
8 years ago
void CBaseMonster::InsertWaypoint( Vector vecLocation, int afMoveFlags )
7 years ago
{
8 years ago
int i, type;
7 years ago
// we have to save some Index and Type information from the real
// path_corner or node waypoint that the monster was trying to reach. This makes sure that data necessary
// to refresh the original path exists even in the new waypoints that don't correspond directy to a path_corner
// or node.
8 years ago
type = afMoveFlags | ( m_Route[m_iRouteIndex].iType & ~bits_MF_NOT_TO_MASK );
7 years ago
8 years ago
for( i = ROUTE_SIZE - 1; i > 0; i-- )
m_Route[i] = m_Route[i - 1];
7 years ago
8 years ago
m_Route[m_iRouteIndex].vecLocation = vecLocation;
m_Route[m_iRouteIndex].iType = type;
7 years ago
}
//=========================================================
// FTriangulate - tries to overcome local obstacles by
// triangulating a path around them.
//
// iApexDist is how far the obstruction that we are trying
// to triangulate around is from the monster.
//=========================================================
8 years ago
BOOL CBaseMonster::FTriangulate( const Vector &vecStart, const Vector &vecEnd, float flDist, CBaseEntity *pTargetEnt, Vector *pApex )
7 years ago
{
Vector vecDir;
Vector vecForward;
Vector vecLeft;// the spot we'll try to triangulate to on the left
Vector vecRight;// the spot we'll try to triangulate to on the right
Vector vecTop;// the spot we'll try to triangulate to on the top
Vector vecBottom;// the spot we'll try to triangulate to on the bottom
Vector vecFarSide;// the spot that we'll move to after hitting the triangulated point, before moving on to our normal goal.
8 years ago
int i;
7 years ago
float sizeX, sizeZ;
// If the hull width is less than 24, use 24 because CheckLocalMove uses a min of
// 24.
sizeX = pev->size.x;
if( sizeX < 24.0f )
sizeX = 24.0f;
else if( sizeX > 48.0f )
sizeX = 48.0f;
7 years ago
sizeZ = pev->size.z;
//if( sizeZ < 24.0f )
// sizeZ = 24.0f;
7 years ago
vecForward = ( vecEnd - vecStart ).Normalize();
8 years ago
Vector vecDirUp( 0, 0, 1 );
vecDir = CrossProduct( vecForward, vecDirUp );
7 years ago
// start checking right about where the object is, picking two equidistant starting points, one on
// the left, one on the right. As we progress through the loop, we'll push these away from the obstacle,
// hoping to find a way around on either side. pev->size.x is added to the ApexDist in order to help select
// an apex point that insures that the monster is sufficiently past the obstacle before trying to turn back
// onto its original course.
vecLeft = pev->origin + ( vecForward * ( flDist + sizeX ) ) - vecDir * ( sizeX * 3 );
vecRight = pev->origin + ( vecForward * ( flDist + sizeX ) ) + vecDir * ( sizeX * 3 );
8 years ago
if( pev->movetype == MOVETYPE_FLY )
7 years ago
{
8 years ago
vecTop = pev->origin + ( vecForward * flDist ) + ( vecDirUp * sizeZ * 3 );
vecBottom = pev->origin + ( vecForward * flDist ) - ( vecDirUp * sizeZ * 3 );
7 years ago
}
8 years ago
vecFarSide = m_Route[m_iRouteIndex].vecLocation;
7 years ago
vecDir = vecDir * sizeX * 2;
8 years ago
if( pev->movetype == MOVETYPE_FLY )
7 years ago
vecDirUp = vecDirUp * sizeZ * 2;
8 years ago
for( i = 0; i < 8; i++ )
7 years ago
{
// Debug, Draw the triangulation
#if 0
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE);
WRITE_COORD( pev->origin.x );
WRITE_COORD( pev->origin.y );
WRITE_COORD( pev->origin.z );
WRITE_COORD( vecRight.x );
WRITE_COORD( vecRight.y );
WRITE_COORD( vecRight.z );
MESSAGE_END();
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE );
WRITE_COORD( pev->origin.x );
WRITE_COORD( pev->origin.y );
WRITE_COORD( pev->origin.z );
WRITE_COORD( vecLeft.x );
WRITE_COORD( vecLeft.y );
WRITE_COORD( vecLeft.z );
MESSAGE_END();
#endif
#if 0
8 years ago
if( pev->movetype == MOVETYPE_FLY )
7 years ago
{
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE );
WRITE_COORD( pev->origin.x );
WRITE_COORD( pev->origin.y );
WRITE_COORD( pev->origin.z );
WRITE_COORD( vecTop.x );
WRITE_COORD( vecTop.y );
WRITE_COORD( vecTop.z );
MESSAGE_END();
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
WRITE_BYTE( TE_SHOWLINE );
WRITE_COORD( pev->origin.x );
WRITE_COORD( pev->origin.y );
WRITE_COORD( pev->origin.z );
WRITE_COORD( vecBottom.x );
WRITE_COORD( vecBottom.y );
WRITE_COORD( vecBottom.z );
MESSAGE_END();
}
#endif
8 years ago
if( CheckLocalMove( pev->origin, vecRight, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( CheckLocalMove( vecRight, vecFarSide, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( pApex )
7 years ago
{
*pApex = vecRight;
}
return TRUE;
}
}
8 years ago
if( CheckLocalMove( pev->origin, vecLeft, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( CheckLocalMove( vecLeft, vecFarSide, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( pApex )
7 years ago
{
*pApex = vecLeft;
}
return TRUE;
}
}
8 years ago
if( pev->movetype == MOVETYPE_FLY )
7 years ago
{
8 years ago
if( CheckLocalMove( pev->origin, vecTop, pTargetEnt, NULL ) == LOCALMOVE_VALID)
7 years ago
{
8 years ago
if( CheckLocalMove ( vecTop, vecFarSide, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( pApex )
7 years ago
{
*pApex = vecTop;
//ALERT(at_aiconsole, "triangulate over\n");
}
return TRUE;
}
}
#if 1
8 years ago
if( CheckLocalMove( pev->origin, vecBottom, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( CheckLocalMove( vecBottom, vecFarSide, pTargetEnt, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( pApex )
7 years ago
{
*pApex = vecBottom;
//ALERT(at_aiconsole, "triangulate under\n");
}
return TRUE;
}
}
#endif
}
vecRight = vecRight + vecDir;
vecLeft = vecLeft - vecDir;
8 years ago
if( pev->movetype == MOVETYPE_FLY )
7 years ago
{
vecTop = vecTop + vecDirUp;
vecBottom = vecBottom - vecDirUp;
}
}
return FALSE;
}
//=========================================================
// Move - take a single step towards the next ROUTE location
//=========================================================
#define DIST_TO_CHECK 200
8 years ago
void CBaseMonster::Move( float flInterval )
7 years ago
{
float flWaypointDist;
float flCheckDist;
float flDist;// how far the lookahead check got before hitting an object.
Vector vecDir;
Vector vecApex;
CBaseEntity *pTargetEnt;
// Don't move if no valid route
8 years ago
if( FRouteClear() )
7 years ago
{
// If we still have a movement goal, then this is probably a route truncated by SimplifyRoute()
// so refresh it.
8 years ago
if( m_movementGoal == MOVEGOAL_NONE || !FRefreshRoute() )
7 years ago
{
ALERT( at_aiconsole, "Tried to move with no route!\n" );
TaskFail();
return;
}
}
8 years ago
if( m_flMoveWaitFinished > gpGlobals->time )
7 years ago
return;
// Debug, test movement code
#if 0
8 years ago
// if( CVAR_GET_FLOAT("stopmove" ) != 0 )
7 years ago
{
8 years ago
if( m_movementGoal == MOVEGOAL_ENEMY )
7 years ago
RouteSimplify( m_hEnemy );
else
RouteSimplify( m_hTargetEnt );
FRefreshRoute();
return;
}
#else
// Debug, draw the route
// DrawRoute( pev, m_Route, m_iRouteIndex, 0, 200, 0 );
#endif
// if the monster is moving directly towards an entity (enemy for instance), we'll set this pointer
// to that entity for the CheckLocalMove and Triangulate functions.
pTargetEnt = NULL;
// local move to waypoint.
8 years ago
vecDir = ( m_Route[m_iRouteIndex].vecLocation - pev->origin ).Normalize();
flWaypointDist = ( m_Route[m_iRouteIndex].vecLocation - pev->origin ).Length2D();
8 years ago
MakeIdealYaw( m_Route[m_iRouteIndex].vecLocation );
ChangeYaw( pev->yaw_speed );
7 years ago
// if the waypoint is closer than CheckDist, CheckDist is the dist to waypoint
8 years ago
if( flWaypointDist < DIST_TO_CHECK )
7 years ago
{
flCheckDist = flWaypointDist;
}
else
{
flCheckDist = DIST_TO_CHECK;
}
8 years ago
if( ( m_Route[m_iRouteIndex].iType & ( ~bits_MF_NOT_TO_MASK ) ) == bits_MF_TO_ENEMY )
7 years ago
{
// only on a PURE move to enemy ( i.e., ONLY MF_TO_ENEMY set, not MF_TO_ENEMY and DETOUR )
pTargetEnt = m_hEnemy;
}
8 years ago
else if( ( m_Route[m_iRouteIndex].iType & ~bits_MF_NOT_TO_MASK ) == bits_MF_TO_TARGETENT )
7 years ago
{
pTargetEnt = m_hTargetEnt;
}
// !!!BUGBUG - CheckDist should be derived from ground speed.
// If this fails, it should be because of some dynamic entity blocking this guy.
// We've already checked this path, so we should wait and time out if the entity doesn't move
flDist = 0;
8 years ago
if( CheckLocalMove( pev->origin, pev->origin + vecDir * flCheckDist, pTargetEnt, &flDist ) != LOCALMOVE_VALID )
7 years ago
{
CBaseEntity *pBlocker;
// Can't move, stop
Stop();
7 years ago
// Blocking entity is in global trace_ent
pBlocker = CBaseEntity::Instance( gpGlobals->trace_ent );
8 years ago
if( pBlocker )
7 years ago
{
DispatchBlocked( edict(), pBlocker->edict() );
}
if( pBlocker && m_moveWaitTime > 0 && pBlocker->IsMoving() && !pBlocker->IsPlayer() && ( gpGlobals->time-m_flMoveWaitFinished ) > 3.0f )
7 years ago
{
// Can we still move toward our target?
8 years ago
if( flDist < m_flGroundSpeed )
7 years ago
{
// No, Wait for a second
m_flMoveWaitFinished = gpGlobals->time + m_moveWaitTime;
return;
}
// Ok, still enough room to take a step
}
else
{
// try to triangulate around whatever is in the way.
8 years ago
if( FTriangulate( pev->origin, m_Route[m_iRouteIndex].vecLocation, flDist, pTargetEnt, &vecApex ) )
7 years ago
{
InsertWaypoint( vecApex, bits_MF_TO_DETOUR );
RouteSimplify( pTargetEnt );
}
else
{
8 years ago
//ALERT( at_aiconsole, "Couldn't Triangulate\n" );
7 years ago
Stop();
7 years ago
// Only do this once until your route is cleared
8 years ago
if( m_moveWaitTime > 0 && !( m_afMemory & bits_MEMORY_MOVE_FAILED ) )
7 years ago
{
FRefreshRoute();
8 years ago
if( FRouteClear() )
7 years ago
{
TaskFail();
}
else
{
// Don't get stuck
if( ( gpGlobals->time - m_flMoveWaitFinished ) < 0.2f )
7 years ago
Remember( bits_MEMORY_MOVE_FAILED );
m_flMoveWaitFinished = gpGlobals->time + 0.1f;
7 years ago
}
}
else
{
TaskFail();
8 years ago
ALERT( at_aiconsole, "%s Failed to move (%d)!\n", STRING( pev->classname ), HasMemory( bits_MEMORY_MOVE_FAILED ) );
//ALERT( at_aiconsole, "%f, %f, %f\n", pev->origin.z, ( pev->origin + ( vecDir * flCheckDist ) ).z, m_Route[m_iRouteIndex].vecLocation.z );
7 years ago
}
return;
}
}
}
// close enough to the target, now advance to the next target. This is done before actually reaching
// the target so that we get a nice natural turn while moving.
8 years ago
if( ShouldAdvanceRoute( flWaypointDist ) )///!!!BUGBUG- magic number
7 years ago
{
AdvanceRoute( flWaypointDist );
}
// Might be waiting for a door
8 years ago
if( m_flMoveWaitFinished > gpGlobals->time )
7 years ago
{
Stop();
return;
}
// UNDONE: this is a hack to quit moving farther than it has looked ahead.
8 years ago
if( flCheckDist < m_flGroundSpeed * flInterval )
7 years ago
{
flInterval = flCheckDist / m_flGroundSpeed;
// ALERT( at_console, "%.02f\n", flInterval );
}
MoveExecute( pTargetEnt, vecDir, flInterval );
8 years ago
if( MovementIsComplete() )
7 years ago
{
Stop();
RouteClear();
}
}
8 years ago
BOOL CBaseMonster::ShouldAdvanceRoute( float flWaypointDist )
7 years ago
{
8 years ago
if( flWaypointDist <= MONSTER_CUT_CORNER_DIST )
7 years ago
{
// ALERT( at_console, "cut %f\n", flWaypointDist );
return TRUE;
}
return FALSE;
}
void CBaseMonster::MoveExecute( CBaseEntity *pTargetEnt, const Vector &vecDir, float flInterval )
{
8 years ago
//float flYaw = UTIL_VecToYaw( m_Route[m_iRouteIndex].vecLocation - pev->origin );// build a yaw that points to the goal.
//WALK_MOVE( ENT( pev ), flYaw, m_flGroundSpeed * flInterval, WALKMOVE_NORMAL );
if( m_IdealActivity != m_movementActivity )
7 years ago
m_IdealActivity = m_movementActivity;
float flTotal = m_flGroundSpeed * pev->framerate * flInterval;
float flStep;
while( flTotal > 0.001f )
7 years ago
{
// don't walk more than 16 units or stairs stop working
flStep = Q_min( 16.0f, flTotal );
8 years ago
UTIL_MoveToOrigin( ENT( pev ), m_Route[m_iRouteIndex].vecLocation, flStep, MOVE_NORMAL );
7 years ago
flTotal -= flStep;
}
// ALERT( at_console, "dist %f\n", m_flGroundSpeed * pev->framerate * flInterval );
}
//=========================================================
// MonsterInit - after a monster is spawned, it needs to
// be dropped into the world, checked for mobility problems,
// and put on the proper path, if any. This function does
// all of those things after the monster spawns. Any
// initialization that should take place for all monsters
// goes here.
//=========================================================
8 years ago
void CBaseMonster::MonsterInit( void )
7 years ago
{
8 years ago
if( !g_pGameRules->FAllowMonsters() )
7 years ago
{
pev->flags |= FL_KILLME; // Post this because some monster code modifies class data after calling this function
8 years ago
//REMOVE_ENTITY( ENT( pev ) );
7 years ago
return;
}
// Set fields common to all monsters
pev->effects = 0;
pev->takedamage = DAMAGE_AIM;
pev->ideal_yaw = pev->angles.y;
pev->max_health = pev->health;
pev->deadflag = DEAD_NO;
m_IdealMonsterState = MONSTERSTATE_IDLE;// Assume monster will be idle, until proven otherwise
m_IdealActivity = ACT_IDLE;
8 years ago
SetBits( pev->flags, FL_MONSTER );
if( pev->spawnflags & SF_MONSTER_HITMONSTERCLIP )
7 years ago
pev->flags |= FL_MONSTERCLIP;
8 years ago
7 years ago
ClearSchedule();
RouteClear();
InitBoneControllers( ); // FIX: should be done in Spawn
8 years ago
m_iHintNode = NO_NODE;
7 years ago
8 years ago
m_afMemory = MEMORY_CLEAR;
7 years ago
8 years ago
m_hEnemy = NULL;
7 years ago
m_flDistTooFar = 1024.0f;
m_flDistLook = 2048.0f;
7 years ago
// set eye position
SetEyePosition();
9 years ago
SetThink( &CBaseMonster::MonsterInitThink );
SetNextThink( 0.1f );
9 years ago
SetUse( &CBaseMonster::MonsterUse );
7 years ago
}
//=========================================================
// MonsterInitThink - Calls StartMonster. Startmonster is
// virtual, but this function cannot be
//=========================================================
8 years ago
void CBaseMonster::MonsterInitThink( void )
7 years ago
{
StartMonster();
}
void CBaseMonster :: StartPatrol ( CBaseEntity* path )
{
m_pGoalEnt = path;
if ( !m_pGoalEnt )
{
ALERT(at_error, "ReadyMonster()--%s couldn't find target \"%s\"\n", STRING(pev->classname), STRING(pev->target));
}
else
{
// Monster will start turning towards his destination
// MakeIdealYaw ( m_pGoalEnt->pev->origin );
// set the monster up to walk a path corner path.
// !!!BUGBUG - this is a minor bit of a hack.
// JAYJAY
m_movementGoal = MOVEGOAL_PATHCORNER;
if ( pev->movetype == MOVETYPE_FLY )
m_movementActivity = ACT_FLY;
else
m_movementActivity = ACT_WALK;
if ( !FRefreshRoute() )
{
ALERT ( at_aiconsole, "Can't Create Route!\n" );
}
SetState( MONSTERSTATE_IDLE );
ChangeSchedule( GetScheduleOfType( SCHED_IDLE_WALK ) );
}
}
//=========================================================
// StartMonster - final bit of initization before a monster
// is turned over to the AI.
//=========================================================
8 years ago
void CBaseMonster::StartMonster( void )
7 years ago
{
// update capabilities
8 years ago
if( LookupActivity( ACT_RANGE_ATTACK1 ) != ACTIVITY_NOT_AVAILABLE )
7 years ago
{
m_afCapability |= bits_CAP_RANGE_ATTACK1;
}
8 years ago
if( LookupActivity( ACT_RANGE_ATTACK2 ) != ACTIVITY_NOT_AVAILABLE )
7 years ago
{
m_afCapability |= bits_CAP_RANGE_ATTACK2;
}
8 years ago
if( LookupActivity( ACT_MELEE_ATTACK1 ) != ACTIVITY_NOT_AVAILABLE )
7 years ago
{
m_afCapability |= bits_CAP_MELEE_ATTACK1;
}
8 years ago
if( LookupActivity( ACT_MELEE_ATTACK2 ) != ACTIVITY_NOT_AVAILABLE )
7 years ago
{
m_afCapability |= bits_CAP_MELEE_ATTACK2;
}
// Raise monster off the floor one unit, then drop to floor
8 years ago
if( pev->movetype != MOVETYPE_FLY && !FBitSet( pev->spawnflags, SF_MONSTER_FALL_TO_GROUND ) )
7 years ago
{
pev->origin.z += 1;
8 years ago
DROP_TO_FLOOR( ENT( pev ) );
7 years ago
// Try to move the monster to make sure it's not stuck in a brush.
//LRC- there are perfectly good reasons for making a monster stuck, so it shouldn't always be an error.
if (!WALK_MOVE ( ENT(pev), 0, 0, WALKMOVE_NORMAL ) && !FBitSet( pev->spawnflags, SF_MONSTER_NO_YELLOW_BLOBS))
{
8 years ago
ALERT( at_error, "Monster %s stuck in wall--level design error\n", STRING( pev->classname ) );
if( g_psv_developer && g_psv_developer->value )
pev->effects = EF_BRIGHTFIELD;
7 years ago
}
}
else
{
pev->flags &= ~FL_ONGROUND;
}
8 years ago
if( !FStringNull( pev->target ) )// this monster has a target
7 years ago
{
StartPatrol(UTIL_FindEntityByTargetname( NULL, STRING( pev->target )));
}
8 years ago
//SetState( m_IdealMonsterState );
//SetActivity( m_IdealActivity );
7 years ago
// Delay drop to floor to make sure each door in the level has had its chance to spawn
// Spread think times so that they don't all happen at the same time (Carmack)
9 years ago
SetThink( &CBaseMonster::CallMonsterThink );
AbsoluteNextThink( m_fNextThink + RANDOM_FLOAT( 0.1f, 0.4f ) ); // spread think times.
// Vit_amiN: fixed -- now it doesn't touch any scripted_sequence target
if( !FStringNull( pev->targetname ) && !m_pCine )// wait until triggered
7 years ago
{
SetState( MONSTERSTATE_IDLE );
// UNDONE: Some scripted sequence monsters don't have an idle?
SetActivity( ACT_IDLE );
ChangeSchedule( GetScheduleOfType( SCHED_WAIT_TRIGGER ) );
}
}
8 years ago
void CBaseMonster::MovementComplete( void )
7 years ago
{
switch( m_iTaskStatus )
{
case TASKSTATUS_NEW:
case TASKSTATUS_RUNNING:
m_iTaskStatus = TASKSTATUS_RUNNING_TASK;
break;
case TASKSTATUS_RUNNING_MOVEMENT:
TaskComplete();
break;
case TASKSTATUS_RUNNING_TASK:
ALERT( at_error, "Movement completed twice!\n" );
break;
case TASKSTATUS_COMPLETE:
break;
}
m_movementGoal = MOVEGOAL_NONE;
}
int CBaseMonster::TaskIsRunning( void )
{
8 years ago
if( m_iTaskStatus != TASKSTATUS_COMPLETE &&
7 years ago
m_iTaskStatus != TASKSTATUS_RUNNING_MOVEMENT )
return 1;
return 0;
}
//=========================================================
// IRelationship - returns an integer that describes the
// relationship between two types of monster.
//=========================================================
8 years ago
int CBaseMonster::IRelationship( CBaseEntity *pTarget )
7 years ago
{
static int iEnemy[17][17] =
{ // NONE MACH PLYR HPASS HMIL AMIL APASS AMONST APREY APRED INSECT PLRALY PBWPN ABWPN FACT_A FACT_B FACT_C
/*NONE*/ { R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO },
/*MACHINE*/ { R_NO, R_NO, R_DL, R_DL, R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL },
/*PLAYER*/ { R_NO, R_DL, R_NO, R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_NO, R_NO, R_DL, R_DL, R_DL, R_DL, R_DL },
/*HUMANPASSIVE*/{ R_NO, R_NO, R_AL, R_AL, R_HT, R_FR, R_NO, R_HT, R_DL, R_FR, R_NO, R_AL, R_NO, R_NO, R_DL, R_DL, R_DL },
/*HUMANMILITAR*/{ R_NO, R_NO, R_HT, R_DL, R_NO, R_HT, R_DL, R_DL, R_DL, R_DL, R_NO, R_HT, R_NO, R_NO, R_DL, R_DL, R_DL },
/*ALIENMILITAR*/{ R_NO, R_DL, R_HT, R_DL, R_HT, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_DL, R_NO, R_NO, R_DL, R_DL, R_DL },
/*ALIENPASSIVE*/{ R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_DL, R_DL, R_DL },
/*ALIENMONSTER*/{ R_NO, R_DL, R_DL, R_DL, R_DL, R_NO, R_NO, R_NO, R_NO, R_NO, R_NO, R_DL, R_NO, R_NO, R_DL, R_DL, R_DL },
/*ALIENPREY */{ R_NO, R_NO, R_DL, R_DL, R_DL, R_NO, R_NO, R_NO, R_NO, R_FR, R_NO, R_DL, R_NO, R_NO, R_DL, R_DL, R_DL },
/*ALIENPREDATO*/{ R_NO, R_NO, R_DL, R_DL, R_DL, R_NO, R_NO, R_NO, R_HT, R_DL, R_NO, R_DL, R_NO, R_NO, R_DL, R_DL, R_DL },
/*INSECT*/ { R_FR, R_FR, R_FR, R_FR, R_FR, R_NO, R_FR, R_FR, R_FR, R_FR, R_NO, R_FR, R_NO, R_NO, R_FR, R_FR, R_FR },
/*PLAYERALLY*/ { R_NO, R_DL, R_AL, R_AL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_NO, R_NO, R_NO, R_NO, R_DL, R_DL, R_DL },
/*PBIOWEAPON*/ { R_NO, R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_NO, R_DL, R_NO, R_DL, R_DL, R_DL, R_DL },
/*ABIOWEAPON*/ { R_NO, R_NO, R_DL, R_DL, R_DL, R_AL, R_NO, R_DL, R_DL, R_NO, R_NO, R_DL, R_DL, R_NO, R_DL, R_DL, R_DL },
/*FACTION_A*/ { R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_NO, R_DL, R_DL, R_DL, R_AL, R_DL, R_DL },
/*FACTION_B*/ { R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_NO, R_DL, R_DL, R_DL, R_DL, R_AL, R_DL },
/*FACTION_C*/ { R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_DL, R_NO, R_DL, R_DL, R_DL, R_DL, R_DL, R_AL }
};
9 years ago
7 years ago
int iTargClass = pTarget->Classify();
if (iTargClass == CLASS_PLAYER && m_iPlayerReact) //LRC
{
if (m_iPlayerReact == 1) // Ignore player
return R_NO;
else if (m_iPlayerReact == 4)
return R_HT;
else if (m_afMemory & bits_MEMORY_PROVOKED)
return R_HT;
else
return R_NO;
}
return iEnemy[ Classify() ][ iTargClass ];
}
//=========================================================
// FindCover - tries to find a nearby node that will hide
// the caller from its enemy.
//
// If supplied, search will return a node at least as far
// away as MinDist, but no farther than MaxDist.
// if MaxDist isn't supplied, it defaults to a reasonable
// value
//=========================================================
// UNDONE: Should this find the nearest node?
//float CGraph::PathLength( int iStart, int iDest, int iHull, int afCapMask )
8 years ago
BOOL CBaseMonster::FindCover( Vector vecThreat, Vector vecViewOffset, float flMinDist, float flMaxDist )
7 years ago
{
int i;
int iMyHullIndex;
int iMyNode;
int iThreatNode;
float flDist;
8 years ago
Vector vecLookersOffset;
7 years ago
TraceResult tr;
8 years ago
if( !flMaxDist )
7 years ago
{
// user didn't supply a MaxDist, so work up a crazy one.
flMaxDist = 784;
}
if( flMinDist > 0.5f * flMaxDist )
7 years ago
{
#if _DEBUG
8 years ago
ALERT( at_console, "FindCover MinDist (%.0f) too close to MaxDist (%.0f)\n", flMinDist, flMaxDist );
7 years ago
#endif
flMinDist = 0.5f * flMaxDist;
7 years ago
}
8 years ago
if( !WorldGraph.m_fGraphPresent || !WorldGraph.m_fGraphPointersSet )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "Graph not ready for findcover!\n" );
7 years ago
return FALSE;
}
iMyNode = WorldGraph.FindNearestNode( pev->origin, this );
iThreatNode = WorldGraph.FindNearestNode ( vecThreat, this );
iMyHullIndex = WorldGraph.HullIndex( this );
8 years ago
if( iMyNode == NO_NODE )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "FindCover() - %s has no nearest node!\n", STRING( pev->classname ) );
7 years ago
return FALSE;
}
8 years ago
if( iThreatNode == NO_NODE )
7 years ago
{
8 years ago
// ALERT( at_aiconsole, "FindCover() - Threat has no nearest node!\n" );
7 years ago
iThreatNode = iMyNode;
// return FALSE;
}
vecLookersOffset = vecThreat + vecViewOffset;// calculate location of enemy's eyes
// we'll do a rough sample to find nodes that are relatively nearby
8 years ago
for( i = 0; i < WorldGraph.m_cNodes; i++ )
7 years ago
{
8 years ago
int nodeNumber = ( i + WorldGraph.m_iLastCoverSearch ) % WorldGraph.m_cNodes;
7 years ago
CNode &node = WorldGraph.Node( nodeNumber );
WorldGraph.m_iLastCoverSearch = nodeNumber + 1; // next monster that searches for cover node will start where we left off here.
// could use an optimization here!!
flDist = ( pev->origin - node.m_vecOrigin ).Length();
// DON'T do the trace check on a node that is farther away than a node that we've already found to
// provide cover! Also make sure the node is within the mins/maxs of the search.
8 years ago
if( flDist >= flMinDist && flDist < flMaxDist )
7 years ago
{
8 years ago
UTIL_TraceLine( node.m_vecOrigin + vecViewOffset, vecLookersOffset, ignore_monsters, ignore_glass, ENT( pev ), &tr );
7 years ago
// if this node will block the threat's line of sight to me...
if( tr.flFraction != 1.0f )
7 years ago
{
// ..and is also closer to me than the threat, or the same distance from myself and the threat the node is good.
8 years ago
if( ( iMyNode == iThreatNode ) || WorldGraph.PathLength( iMyNode, nodeNumber, iMyHullIndex, m_afCapability ) <= WorldGraph.PathLength( iThreatNode, nodeNumber, iMyHullIndex, m_afCapability ) )
7 years ago
{
8 years ago
if( FValidateCover( node.m_vecOrigin ) && MoveToLocation( ACT_RUN, 0, node.m_vecOrigin ) )
7 years ago
{
/*
MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY );
8 years ago
WRITE_BYTE( TE_SHOWLINE );
7 years ago
WRITE_COORD( node.m_vecOrigin.x );
WRITE_COORD( node.m_vecOrigin.y );
WRITE_COORD( node.m_vecOrigin.z );
WRITE_COORD( vecLookersOffset.x );
WRITE_COORD( vecLookersOffset.y );
WRITE_COORD( vecLookersOffset.z );
MESSAGE_END();
*/
return TRUE;
}
}
}
}
}
return FALSE;
}
//=========================================================
// BuildNearestRoute - tries to build a route as close to the target
// as possible, even if there isn't a path to the final point.
//
// If supplied, search will return a node at least as far
// away as MinDist from vecThreat, but no farther than MaxDist.
// if MaxDist isn't supplied, it defaults to a reasonable
// value
//=========================================================
8 years ago
BOOL CBaseMonster::BuildNearestRoute( Vector vecThreat, Vector vecViewOffset, float flMinDist, float flMaxDist )
7 years ago
{
int i;
int iMyHullIndex;
int iMyNode;
float flDist;
8 years ago
Vector vecLookersOffset;
7 years ago
TraceResult tr;
8 years ago
if( !flMaxDist )
7 years ago
{
// user didn't supply a MaxDist, so work up a crazy one.
flMaxDist = 784;
}
if( flMinDist > 0.5f * flMaxDist )
7 years ago
{
#if _DEBUG
8 years ago
ALERT( at_console, "FindCover MinDist (%.0f) too close to MaxDist (%.0f)\n", flMinDist, flMaxDist );
7 years ago
#endif
flMinDist = 0.5f * flMaxDist;
7 years ago
}
8 years ago
if( !WorldGraph.m_fGraphPresent || !WorldGraph.m_fGraphPointersSet )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "Graph not ready for BuildNearestRoute!\n" );
7 years ago
return FALSE;
}
iMyNode = WorldGraph.FindNearestNode( pev->origin, this );
iMyHullIndex = WorldGraph.HullIndex( this );
8 years ago
if( iMyNode == NO_NODE )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "BuildNearestRoute() - %s has no nearest node!\n", STRING( pev->classname ) );
7 years ago
return FALSE;
}
vecLookersOffset = vecThreat + vecViewOffset;// calculate location of enemy's eyes
// we'll do a rough sample to find nodes that are relatively nearby
8 years ago
for( i = 0; i < WorldGraph.m_cNodes; i++ )
7 years ago
{
8 years ago
int nodeNumber = ( i + WorldGraph.m_iLastCoverSearch ) % WorldGraph.m_cNodes;
7 years ago
CNode &node = WorldGraph.Node( nodeNumber );
WorldGraph.m_iLastCoverSearch = nodeNumber + 1; // next monster that searches for cover node will start where we left off here.
// can I get there?
8 years ago
if( WorldGraph.NextNodeInRoute( iMyNode, nodeNumber, iMyHullIndex, 0 ) != iMyNode )
7 years ago
{
flDist = ( vecThreat - node.m_vecOrigin ).Length();
// is it close?
8 years ago
if( flDist > flMinDist && flDist < flMaxDist )
7 years ago
{
// can I see where I want to be from there?
UTIL_TraceLine( node.m_vecOrigin + pev->view_ofs, vecLookersOffset, ignore_monsters, edict(), &tr );
if( tr.flFraction == 1.0f )
7 years ago
{
// try to actually get there
8 years ago
if( BuildRoute( node.m_vecOrigin, bits_MF_TO_LOCATION, NULL ) )
7 years ago
{
// flMaxDist = flDist;
7 years ago
m_vecMoveGoal = node.m_vecOrigin;
return TRUE; // UNDONE: keep looking for something closer!
}
}
}
}
}
return FALSE;
}
//=========================================================
// BestVisibleEnemy - this functions searches the link
// list whose head is the caller's m_pLink field, and returns
// a pointer to the enemy entity in that list that is nearest the
// caller.
//
// !!!UNDONE - currently, this only returns the closest enemy.
// we'll want to consider distance, relationship, attack types, back turned, etc.
//=========================================================
8 years ago
CBaseEntity *CBaseMonster::BestVisibleEnemy( void )
7 years ago
{
CBaseEntity *pReturn;
CBaseEntity *pNextEnt;
8 years ago
int iNearest;
int iDist;
int iBestRelationship;
7 years ago
iNearest = 8192;// so first visible entity will become the closest.
pNextEnt = m_pLink;
pReturn = NULL;
iBestRelationship = R_NO;
8 years ago
while( pNextEnt != NULL )
7 years ago
{
8 years ago
if( pNextEnt->IsAlive() )
7 years ago
{
8 years ago
if( IRelationship( pNextEnt) > iBestRelationship )
7 years ago
{
// this entity is disliked MORE than the entity that we
// currently think is the best visible enemy. No need to do
// a distance check, just get mad at this one for now.
iBestRelationship = IRelationship ( pNextEnt );
iNearest = ( pNextEnt->pev->origin - pev->origin ).Length();
pReturn = pNextEnt;
}
8 years ago
else if( IRelationship( pNextEnt) == iBestRelationship )
7 years ago
{
// this entity is disliked just as much as the entity that
// we currently think is the best visible enemy, so we only
// get mad at it if it is closer.
iDist = ( pNextEnt->pev->origin - pev->origin ).Length();
8 years ago
if( iDist <= iNearest )
7 years ago
{
iNearest = iDist;
8 years ago
iBestRelationship = IRelationship( pNextEnt );
7 years ago
pReturn = pNextEnt;
}
}
}
pNextEnt = pNextEnt->m_pLink;
}
return pReturn;
}
//=========================================================
// MakeIdealYaw - gets a yaw value for the caller that would
// face the supplied vector. Value is stuffed into the monster's
// ideal_yaw
//=========================================================
8 years ago
void CBaseMonster::MakeIdealYaw( Vector vecTarget )
7 years ago
{
8 years ago
Vector vecProjection;
7 years ago
// strafing monster needs to face 90 degrees away from its goal
8 years ago
if( m_movementActivity == ACT_STRAFE_LEFT )
7 years ago
{
vecProjection.x = -vecTarget.y;
vecProjection.y = vecTarget.x;
pev->ideal_yaw = UTIL_VecToYaw( vecProjection - pev->origin );
}
8 years ago
else if( m_movementActivity == ACT_STRAFE_RIGHT )
7 years ago
{
vecProjection.x = vecTarget.y;
vecProjection.y = vecTarget.x;
pev->ideal_yaw = UTIL_VecToYaw( vecProjection - pev->origin );
}
else
{
8 years ago
pev->ideal_yaw = UTIL_VecToYaw( vecTarget - pev->origin );
7 years ago
}
}
//=========================================================
// FlYawDiff - returns the difference ( in degrees ) between
// monster's current yaw and ideal_yaw
//
// Positive result is left turn, negative is right turn
//=========================================================
8 years ago
float CBaseMonster::FlYawDiff( void )
7 years ago
{
8 years ago
float flCurrentYaw;
7 years ago
flCurrentYaw = UTIL_AngleMod( pev->angles.y );
8 years ago
if( flCurrentYaw == pev->ideal_yaw )
7 years ago
{
return 0;
}
return UTIL_AngleDiff( pev->ideal_yaw, flCurrentYaw );
}
//=========================================================
// Changeyaw - turns a monster towards its ideal_yaw
//=========================================================
8 years ago
float CBaseMonster::ChangeYaw( int yawSpeed )
7 years ago
{
float ideal, current, move, speed;
current = UTIL_AngleMod( pev->angles.y );
ideal = pev->ideal_yaw;
8 years ago
if( current != ideal )
7 years ago
{
speed = (float)yawSpeed * gpGlobals->frametime * 10;
move = ideal - current;
8 years ago
if( ideal > current )
7 years ago
{
8 years ago
if( move >= 180 )
7 years ago
move = move - 360;
}
else
{
8 years ago
if( move <= -180 )
7 years ago
move = move + 360;
}
8 years ago
if( move > 0 )
{
// turning to the monster's left
8 years ago
if( move > speed )
7 years ago
move = speed;
}
else
{
// turning to the monster's right
8 years ago
if( move < -speed )
7 years ago
move = -speed;
}
8 years ago
pev->angles.y = UTIL_AngleMod( current + move );
7 years ago
// turn head in desired direction only if they have a turnable head
8 years ago
if( m_afCapability & bits_CAP_TURN_HEAD )
7 years ago
{
float yaw = pev->ideal_yaw - pev->angles.y;
8 years ago
if( yaw > 180 )
yaw -= 360;
if( yaw < -180 )
yaw += 360;
7 years ago
// yaw *= 0.8;
SetBoneController( 0, yaw );
}
}
else
move = 0;
return move;
}
//=========================================================
// VecToYaw - turns a directional vector into a yaw value
// that points down that vector.
//=========================================================
8 years ago
float CBaseMonster::VecToYaw( Vector vecDir )
7 years ago
{
8 years ago
if( vecDir.x == 0 && vecDir.y == 0 && vecDir.z == 0 )
7 years ago
return pev->angles.y;
return UTIL_VecToYaw( vecDir );
}
//=========================================================
// SetEyePosition
//
// queries the monster's model for $eyeposition and copies
// that vector to the monster's view_ofs
//
//=========================================================
8 years ago
void CBaseMonster::SetEyePosition( void )
7 years ago
{
Vector vecEyePosition;
void *pmodel = GET_MODEL_PTR( ENT(pev) );
GetEyePosition( pmodel, vecEyePosition );
pev->view_ofs = vecEyePosition;
8 years ago
if( pev->view_ofs == g_vecZero )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "%s has no view_ofs!\n", STRING( pev->classname ) );
7 years ago
}
}
8 years ago
void CBaseMonster::HandleAnimEvent( MonsterEvent_t *pEvent )
7 years ago
{
switch( pEvent->event )
{
case SCRIPT_EVENT_DEAD:
8 years ago
if( m_MonsterState == MONSTERSTATE_SCRIPT )
7 years ago
{
pev->deadflag = DEAD_DYING;
// Kill me now! (and fade out when CineCleanup() is called)
#if _DEBUG
8 years ago
ALERT( at_aiconsole, "Death event: %s\n", STRING( pev->classname ) );
7 years ago
#endif
pev->health = 0;
}
#if _DEBUG
else
8 years ago
ALERT( at_aiconsole, "INVALID death event:%s\n", STRING( pev->classname ) );
7 years ago
#endif
break;
case SCRIPT_EVENT_NOT_DEAD:
8 years ago
if( m_MonsterState == MONSTERSTATE_SCRIPT )
7 years ago
{
pev->deadflag = DEAD_NO;
7 years ago
// This is for life/death sequences where the player can determine whether a character is dead or alive after the script
pev->health = pev->max_health;
}
break;
case SCRIPT_EVENT_SOUND: // Play a named wave file
if ( !(pev->spawnflags & SF_MONSTER_GAG) || m_MonsterState != MONSTERSTATE_IDLE)
9 years ago
EMIT_SOUND( edict(), CHAN_BODY, pEvent->options, 1.0, ATTN_IDLE );
7 years ago
break;
case SCRIPT_EVENT_SOUND_VOICE:
if ( !(pev->spawnflags & SF_MONSTER_GAG) || m_MonsterState != MONSTERSTATE_IDLE)
9 years ago
EMIT_SOUND( edict(), CHAN_VOICE, pEvent->options, 1.0, ATTN_IDLE );
7 years ago
break;
case SCRIPT_EVENT_SENTENCE_RND1: // Play a named sentence group 33% of the time
8 years ago
if( RANDOM_LONG( 0, 2 ) == 0 )
7 years ago
break;
// fall through...
case SCRIPT_EVENT_SENTENCE: // Play a named sentence group
SENTENCEG_PlayRndSz( edict(), pEvent->options, 1.0, ATTN_IDLE, 0, 100 );
break;
case SCRIPT_EVENT_FIREEVENT: // Fire a trigger
FireTargets( pEvent->options, this, this, USE_TOGGLE, 0 );
break;
case SCRIPT_EVENT_NOINTERRUPT: // Can't be interrupted from now on
8 years ago
if( m_pCine )
7 years ago
m_pCine->AllowInterrupt( FALSE );
break;
case SCRIPT_EVENT_CANINTERRUPT: // OK to interrupt now
8 years ago
if( m_pCine )
7 years ago
m_pCine->AllowInterrupt( TRUE );
break;
#if 0
case SCRIPT_EVENT_INAIR: // Don't DROP_TO_FLOOR()
case SCRIPT_EVENT_ENDANIMATION: // Set ending animation sequence to
break;
#endif
case MONSTER_EVENT_BODYDROP_HEAVY:
8 years ago
if( pev->flags & FL_ONGROUND )
7 years ago
{
8 years ago
if( RANDOM_LONG( 0, 1 ) == 0 )
7 years ago
{
8 years ago
EMIT_SOUND_DYN( ENT( pev ), CHAN_BODY, "common/bodydrop3.wav", 1, ATTN_NORM, 0, 90 );
7 years ago
}
else
{
8 years ago
EMIT_SOUND_DYN( ENT( pev ), CHAN_BODY, "common/bodydrop4.wav", 1, ATTN_NORM, 0, 90 );
7 years ago
}
}
break;
case MONSTER_EVENT_BODYDROP_LIGHT:
8 years ago
if( pev->flags & FL_ONGROUND )
7 years ago
{
8 years ago
if( RANDOM_LONG( 0, 1 ) == 0 )
7 years ago
{
8 years ago
EMIT_SOUND( ENT( pev ), CHAN_BODY, "common/bodydrop3.wav", 1, ATTN_NORM );
7 years ago
}
else
{
8 years ago
EMIT_SOUND( ENT( pev ), CHAN_BODY, "common/bodydrop4.wav", 1, ATTN_NORM );
7 years ago
}
}
break;
case MONSTER_EVENT_SWISHSOUND:
{
// NO MONSTER may use this anim event unless that monster's precache precaches this sound!!!
8 years ago
EMIT_SOUND( ENT( pev ), CHAN_BODY, "zombie/claw_miss2.wav", 1, ATTN_NORM );
7 years ago
break;
}
default:
8 years ago
ALERT( at_aiconsole, "Unhandled animation event %d for %s\n", pEvent->event, STRING( pev->classname ) );
7 years ago
break;
}
}
// Combat
8 years ago
Vector CBaseMonster::GetGunPosition()
7 years ago
{
8 years ago
UTIL_MakeVectors( pev->angles );
7 years ago
// Vector vecSrc = pev->origin + gpGlobals->v_forward * 10;
//vecSrc.z = pevShooter->absmin.z + pevShooter->size.z * 0.7;
//vecSrc.z = pev->origin.z + (pev->view_ofs.z - 4);
Vector vecSrc = pev->origin
+ gpGlobals->v_forward * m_HackedGunPos.y
+ gpGlobals->v_right * m_HackedGunPos.x
+ gpGlobals->v_up * m_HackedGunPos.z;
return vecSrc;
}
//=========================================================
// NODE GRAPH
//=========================================================
//=========================================================
// FGetNodeRoute - tries to build an entire node path from
// the callers origin to the passed vector. If this is
// possible, ROUTE_SIZE waypoints will be copied into the
// callers m_Route. TRUE is returned if the operation
// succeeds (path is valid) or FALSE if failed (no path
// exists )
//=========================================================
8 years ago
BOOL CBaseMonster::FGetNodeRoute( Vector vecDest )
7 years ago
{
int iPath[ MAX_PATH_SIZE ];
int iSrcNode, iDestNode;
int iResult;
int i;
int iNumToCopy;
8 years ago
iSrcNode = WorldGraph.FindNearestNode( pev->origin, this );
iDestNode = WorldGraph.FindNearestNode( vecDest, this );
7 years ago
8 years ago
if( iSrcNode == -1 )
7 years ago
{
// no node nearest self
8 years ago
//ALERT( at_aiconsole, "FGetNodeRoute: No valid node near self!\n" );
7 years ago
return FALSE;
}
8 years ago
else if( iDestNode == -1 )
7 years ago
{
// no node nearest target
8 years ago
//ALERT( at_aiconsole, "FGetNodeRoute: No valid node near target!\n" );
7 years ago
return FALSE;
}
// valid src and dest nodes were found, so it's safe to proceed with
// find shortest path
int iNodeHull = WorldGraph.HullIndex( this ); // make this a monster virtual function
8 years ago
iResult = WorldGraph.FindShortestPath( iPath, iSrcNode, iDestNode, iNodeHull, m_afCapability );
7 years ago
8 years ago
if( !iResult )
7 years ago
{
#if 1
8 years ago
ALERT( at_aiconsole, "No Path from %d to %d!\n", iSrcNode, iDestNode );
7 years ago
return FALSE;
#else
BOOL bRoutingSave = WorldGraph.m_fRoutingComplete;
WorldGraph.m_fRoutingComplete = FALSE;
8 years ago
iResult = WorldGraph.FindShortestPath( iPath, iSrcNode, iDestNode, iNodeHull, m_afCapability );
7 years ago
WorldGraph.m_fRoutingComplete = bRoutingSave;
8 years ago
if( !iResult )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "No Path from %d to %d!\n", iSrcNode, iDestNode );
7 years ago
return FALSE;
}
else
{
8 years ago
ALERT( at_aiconsole, "Routing is inconsistent!" );
7 years ago
}
#endif
}
// there's a valid path within iPath now, so now we will fill the route array
// up with as many of the waypoints as it will hold.
// don't copy ROUTE_SIZE entries if the path returned is shorter
// than ROUTE_SIZE!!!
8 years ago
if( iResult < ROUTE_SIZE )
7 years ago
{
iNumToCopy = iResult;
}
else
{
iNumToCopy = ROUTE_SIZE;
}
8 years ago
for( i = 0 ; i < iNumToCopy; i++ )
7 years ago
{
8 years ago
m_Route[i].vecLocation = WorldGraph.m_pNodes[iPath[i]].m_vecOrigin;
m_Route[i].iType = bits_MF_TO_NODE;
7 years ago
}
8 years ago
if( iNumToCopy < ROUTE_SIZE )
7 years ago
{
8 years ago
m_Route[iNumToCopy].vecLocation = vecDest;
m_Route[iNumToCopy].iType |= bits_MF_IS_GOAL;
7 years ago
}
return TRUE;
}
//=========================================================
// FindHintNode
//=========================================================
8 years ago
int CBaseMonster::FindHintNode( void )
7 years ago
{
int i;
TraceResult tr;
8 years ago
if( !WorldGraph.m_fGraphPresent )
7 years ago
{
8 years ago
ALERT( at_aiconsole, "find_hintnode: graph not ready!\n" );
7 years ago
return NO_NODE;
}
8 years ago
if( WorldGraph.m_iLastActiveIdleSearch >= WorldGraph.m_cNodes )
7 years ago
{
WorldGraph.m_iLastActiveIdleSearch = 0;
}
8 years ago
for( i = 0; i < WorldGraph.m_cNodes; i++ )
7 years ago
{
8 years ago
int nodeNumber = ( i + WorldGraph.m_iLastActiveIdleSearch) % WorldGraph.m_cNodes;
7 years ago
CNode &node = WorldGraph.Node( nodeNumber );
8 years ago
if( node.m_sHintType )
7 years ago
{
// this node has a hint. Take it if it is visible, the monster likes it, and the monster has an animation to match the hint's activity.
8 years ago
if( FValidateHintType( node.m_sHintType ) )
7 years ago
{
8 years ago
if( !node.m_sHintActivity || LookupActivity( node.m_sHintActivity ) != ACTIVITY_NOT_AVAILABLE )
7 years ago
{
8 years ago
UTIL_TraceLine( pev->origin + pev->view_ofs, node.m_vecOrigin + pev->view_ofs, ignore_monsters, ENT( pev ), &tr );
7 years ago
if( tr.flFraction == 1.0f )
7 years ago
{
WorldGraph.m_iLastActiveIdleSearch = nodeNumber + 1; // next monster that searches for hint nodes will start where we left off.
return nodeNumber;// take it!
}
}
}
}
}
WorldGraph.m_iLastActiveIdleSearch = 0;// start at the top of the list for the next search.
return NO_NODE;
}
7 years ago
void CBaseMonster::ReportAIState( void )
{
ALERT_TYPE level = at_console;
static const char *pStateNames[] = { "None", "Idle", "Combat", "Alert", "Hunt", "Prone", "Scripted", "Dead" };
ALERT( level, "%s: ", STRING(pev->classname) );
8 years ago
if( (int)m_MonsterState < ARRAYSIZE( pStateNames ) )
7 years ago
ALERT( level, "State: %s, ", pStateNames[m_MonsterState] );
int i = 0;
8 years ago
while( activity_map[i].type != 0 )
7 years ago
{
8 years ago
if( activity_map[i].type == (int)m_Activity )
7 years ago
{
ALERT( level, "Activity %s, ", activity_map[i].name );
break;
}
i++;
}
8 years ago
if( m_pSchedule )
7 years ago
{
const char *pName = NULL;
pName = m_pSchedule->pName;
8 years ago
if( !pName )
7 years ago
pName = "Unknown";
ALERT( level, "Schedule %s, ", pName );
Task_t *pTask = GetTask();
8 years ago
if( pTask )
7 years ago
ALERT( level, "Task %d (#%d), ", pTask->iTask, m_iScheduleIndex );
}
else
ALERT( level, "No Schedule, " );
if( m_hEnemy != 0 )
8 years ago
ALERT( level, "\nEnemy is %s", STRING( m_hEnemy->pev->classname ) );
7 years ago
else
ALERT( level, "No enemy" );
8 years ago
if( IsMoving() )
7 years ago
{
ALERT( level, " Moving " );
8 years ago
if( m_flMoveWaitFinished > gpGlobals->time )
ALERT( level, ": Stopped for %.2f. ", (double)(m_flMoveWaitFinished - gpGlobals->time) );
8 years ago
else if( m_IdealActivity == GetStoppedActivity() )
7 years ago
ALERT( level, ": In stopped anim. " );
}
CSquadMonster *pSquadMonster = MySquadMonsterPointer();
8 years ago
if( pSquadMonster )
7 years ago
{
8 years ago
if( !pSquadMonster->InSquad() )
7 years ago
{
8 years ago
ALERT( level, "not " );
7 years ago
}
8 years ago
ALERT( level, "In Squad, " );
7 years ago
8 years ago
if( !pSquadMonster->IsLeader() )
7 years ago
{
8 years ago
ALERT( level, "not " );
7 years ago
}
8 years ago
ALERT( level, "Leader." );
7 years ago
}
ALERT( level, "\n" );
ALERT( level, "Yaw speed:%3.1f,Health: %3.1f\n", (double)pev->yaw_speed, (double)pev->health );
8 years ago
if( pev->spawnflags & SF_MONSTER_PRISONER )
7 years ago
ALERT( level, " PRISONER! " );
8 years ago
if( pev->spawnflags & SF_MONSTER_PREDISASTER )
7 years ago
ALERT( level, " Pre-Disaster! " );
ALERT( level, "\n" );
}
//=========================================================
// KeyValue
//
// !!! netname entvar field is used in squadmonster for groupname!!!
//=========================================================
8 years ago
void CBaseMonster::KeyValue( KeyValueData *pkvd )
7 years ago
{
8 years ago
if( FStrEq( pkvd->szKeyName, "TriggerTarget" ) )
7 years ago
{
m_iszTriggerTarget = ALLOC_STRING( pkvd->szValue );
pkvd->fHandled = TRUE;
}
8 years ago
else if( FStrEq( pkvd->szKeyName, "TriggerCondition" ) )
7 years ago
{
m_iTriggerCondition = atoi( pkvd->szValue );
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "m_iClass") ) //LRC
{
m_iClass = atoi( pkvd->szValue );
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "m_iPlayerReact") ) //LRC
{
m_iPlayerReact = atoi( pkvd->szValue );
pkvd->fHandled = TRUE;
}
else
{
CBaseToggle::KeyValue( pkvd );
}
}
//=========================================================
// FCheckAITrigger - checks the monster's AI Trigger Conditions,
// if there is a condition, then checks to see if condition is
// met. If yes, the monster's TriggerTarget is fired.
//
// Returns TRUE if the target is fired.
//=========================================================
8 years ago
BOOL CBaseMonster::FCheckAITrigger( void )
7 years ago
{
BOOL fFireTarget;
8 years ago
if( m_iTriggerCondition == AITRIGGER_NONE )
7 years ago
{
// no conditions, so this trigger is never fired.
return FALSE;
}
fFireTarget = FALSE;
8 years ago
switch( m_iTriggerCondition )
7 years ago
{
case AITRIGGER_SEEPLAYER_ANGRY_AT_PLAYER:
if( m_hEnemy != 0 && m_hEnemy->IsPlayer() && HasConditions( bits_COND_SEE_ENEMY ) )
7 years ago
{
fFireTarget = TRUE;
}
break;
case AITRIGGER_SEEPLAYER_UNCONDITIONAL:
8 years ago
if( HasConditions( bits_COND_SEE_CLIENT ) )
7 years ago
{
fFireTarget = TRUE;
}
break;
case AITRIGGER_SEEPLAYER_NOT_IN_COMBAT:
8 years ago
if( HasConditions( bits_COND_SEE_CLIENT ) &&
7 years ago
m_MonsterState != MONSTERSTATE_COMBAT &&
m_MonsterState != MONSTERSTATE_PRONE &&
m_MonsterState != MONSTERSTATE_SCRIPT)
{
fFireTarget = TRUE;
}
break;
case AITRIGGER_TAKEDAMAGE:
8 years ago
if( m_afConditions & ( bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE ) )
7 years ago
{
fFireTarget = TRUE;
}
break;
case AITRIGGER_DEATH:
8 years ago
if( pev->deadflag != DEAD_NO )
7 years ago
{
fFireTarget = TRUE;
}
break;
case AITRIGGER_HALFHEALTH:
8 years ago
if( IsAlive() && pev->health <= ( pev->max_health / 2 ) )
7 years ago
{
fFireTarget = TRUE;
}
break;
/*
// !!!UNDONE - no persistant game state that allows us to track these two.
case AITRIGGER_SQUADMEMBERDIE:
break;
case AITRIGGER_SQUADLEADERDIE:
break;
*/
case AITRIGGER_HEARWORLD:
8 years ago
if( m_afConditions & bits_COND_HEAR_SOUND && m_afSoundTypes & bits_SOUND_WORLD )
7 years ago
{
fFireTarget = TRUE;
}
break;
case AITRIGGER_HEARPLAYER:
8 years ago
if( m_afConditions & bits_COND_HEAR_SOUND && m_afSoundTypes & bits_SOUND_PLAYER )
7 years ago
{
fFireTarget = TRUE;
}
break;
case AITRIGGER_HEARCOMBAT:
8 years ago
if( m_afConditions & bits_COND_HEAR_SOUND && m_afSoundTypes & bits_SOUND_COMBAT )
7 years ago
{
fFireTarget = TRUE;
}
break;
}
8 years ago
if( fFireTarget )
7 years ago
{
// fire the target, then set the trigger conditions to NONE so we don't fire again
8 years ago
ALERT( at_aiconsole, "AI Trigger Fire Target\n" );
7 years ago
FireTargets( STRING( m_iszTriggerTarget ), this, this, USE_TOGGLE, 0 );
m_iTriggerCondition = AITRIGGER_NONE;
return TRUE;
}
return FALSE;
}
//=========================================================
// CanPlaySequence - determines whether or not the monster
// can play the scripted sequence or AI sequence that is
// trying to possess it. If DisregardState is set, the monster
// will be sucked into the script no matter what state it is
// in. ONLY Scripted AI ents should allow this.
//=========================================================
//LRC - to help debug when sequences won't play...
#define DEBUG_CANTPLAY
int CBaseMonster :: CanPlaySequence( int interruptFlags )
{
if ( m_pCine )
{
if ( interruptFlags & SS_INTERRUPT_SCRIPTS )
{
return true;
}
else
{
7 years ago
#ifdef DEBUG_CANTPLAY
ALERT(at_console, "CANTPLAY: Already playing %s \"%s\"!\n", STRING(m_pCine->pev->classname), STRING(m_pCine->pev->targetname));
7 years ago
#endif
return false;
}
}
else if ( !IsAlive() || m_MonsterState == MONSTERSTATE_PRONE )
{
#ifdef DEBUG_CANTPLAY
ALERT(at_console, "CANTPLAY: Dead/Barnacled!\n");
7 years ago
#endif
// monster is already running a scripted sequence or dead!
return FALSE;
}
if ( interruptFlags & SS_INTERRUPT_ANYSTATE )
{
// ok to go, no matter what the monster state. (scripted AI)
return TRUE;
}
8 years ago
if( m_MonsterState == MONSTERSTATE_NONE || m_MonsterState == MONSTERSTATE_IDLE || m_IdealMonsterState == MONSTERSTATE_IDLE )
7 years ago
{
// ok to go, but only in these states
return TRUE;
}
if ( m_MonsterState == MONSTERSTATE_ALERT && interruptFlags & SS_INTERRUPT_ALERT )
return TRUE;
// unknown situation
#ifdef DEBUG_CANTPLAY
ALERT(at_console, "CANTPLAY: non-interruptable state.\n");
7 years ago
#endif
return FALSE;
}
//=========================================================
// FindLateralCover - attempts to locate a spot in the world
// directly to the left or right of the caller that will
// conceal them from view of pSightEnt
//=========================================================
#define COVER_CHECKS 5// how many checks are made
#define COVER_DELTA 48// distance between checks
8 years ago
BOOL CBaseMonster::FindLateralCover( const Vector &vecThreat, const Vector &vecViewOffset )
7 years ago
{
8 years ago
TraceResult tr;
7 years ago
Vector vecBestOnLeft;
Vector vecBestOnRight;
Vector vecLeftTest;
Vector vecRightTest;
Vector vecStepRight;
8 years ago
int i;
7 years ago
8 years ago
UTIL_MakeVectors( pev->angles );
7 years ago
vecStepRight = gpGlobals->v_right * COVER_DELTA;
vecStepRight.z = 0;
7 years ago
vecLeftTest = vecRightTest = pev->origin;
8 years ago
for( i = 0; i < COVER_CHECKS; i++ )
7 years ago
{
vecLeftTest = vecLeftTest - vecStepRight;
vecRightTest = vecRightTest + vecStepRight;
// it's faster to check the SightEnt's visibility to the potential spot than to check the local move, so we do that first.
8 years ago
UTIL_TraceLine( vecThreat + vecViewOffset, vecLeftTest + pev->view_ofs, ignore_monsters, ignore_glass, ENT( pev )/*pentIgnore*/, &tr );
if( tr.flFraction != 1.0f )
7 years ago
{
8 years ago
if( FValidateCover( vecLeftTest ) && CheckLocalMove( pev->origin, vecLeftTest, NULL, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( MoveToLocation( ACT_RUN, 0, vecLeftTest ) )
7 years ago
{
return TRUE;
}
}
}
// it's faster to check the SightEnt's visibility to the potential spot than to check the local move, so we do that first.
8 years ago
UTIL_TraceLine( vecThreat + vecViewOffset, vecRightTest + pev->view_ofs, ignore_monsters, ignore_glass, ENT(pev)/*pentIgnore*/, &tr );
if( tr.flFraction != 1.0f )
7 years ago
{
8 years ago
if( FValidateCover( vecRightTest ) && CheckLocalMove( pev->origin, vecRightTest, NULL, NULL ) == LOCALMOVE_VALID )
7 years ago
{
8 years ago
if( MoveToLocation( ACT_RUN, 0, vecRightTest ) )
7 years ago
{
return TRUE;
}
}
}
}
return FALSE;
}
8 years ago
Vector CBaseMonster::ShootAtEnemy( const Vector &shootOrigin )
7 years ago
{
if (m_pCine != 0 && m_hTargetEnt != 0 && (m_pCine->m_fTurnType == 1))
7 years ago
{
Vector vecDest = ( m_hTargetEnt->pev->absmin + m_hTargetEnt->pev->absmax ) / 2;
return ( vecDest - shootOrigin ).Normalize();
}
else if ( m_hEnemy )
{
return ( (m_hEnemy->BodyTarget( shootOrigin ) - m_hEnemy->pev->origin) + m_vecEnemyLKP - shootOrigin ).Normalize();
}
9 years ago
else
return gpGlobals->v_forward;
7 years ago
}
//=========================================================
// FacingIdeal - tells us if a monster is facing its ideal
// yaw. Created this function because many spots in the
// code were checking the yawdiff against this magic
// number. Nicer to have it in one place if we're gonna
// be stuck with it.
//=========================================================
8 years ago
BOOL CBaseMonster::FacingIdeal( void )
7 years ago
{
if( fabs( FlYawDiff() ) <= 0.006f )//!!!BUGBUG - no magic numbers!!!
7 years ago
{
return TRUE;
}
return FALSE;
}
//=========================================================
// FCanActiveIdle
//=========================================================
8 years ago
BOOL CBaseMonster::FCanActiveIdle( void )
7 years ago
{
/*
8 years ago
if( m_MonsterState == MONSTERSTATE_IDLE && m_IdealMonsterState == MONSTERSTATE_IDLE && !IsMoving() )
7 years ago
{
return TRUE;
}
*/
return FALSE;
}
void CBaseMonster::PlaySentence( const char *pszSentence, float duration, float volume, float attenuation )
{
8 years ago
if( pszSentence && IsAlive() )
7 years ago
{
8 years ago
if( pszSentence[0] == '!' )
7 years ago
EMIT_SOUND_DYN( edict(), CHAN_VOICE, pszSentence, volume, attenuation, 0, PITCH_NORM );
else
SENTENCEG_PlayRndSz( edict(), pszSentence, volume, attenuation, 0, PITCH_NORM );
}
}
void CBaseMonster::PlayScriptedSentence( const char *pszSentence, float duration, float volume, float attenuation, BOOL bConcurrent, CBaseEntity *pListener )
{
7 years ago
PlaySentence( pszSentence, duration, volume, attenuation );
}
void CBaseMonster::SentenceStop( void )
{
EMIT_SOUND( edict(), CHAN_VOICE, "common/null.wav", 1.0, ATTN_IDLE );
}
void CBaseMonster::CorpseFallThink( void )
{
8 years ago
if( pev->flags & FL_ONGROUND )
7 years ago
{
9 years ago
SetThink( NULL );
7 years ago
SetSequenceBox( );
UTIL_SetOrigin( this, pev->origin );// link into world.
}
else
SetNextThink( 0.1f );
7 years ago
}
// Call after animation/pose is set up
8 years ago
void CBaseMonster::MonsterInitDead( void )
7 years ago
{
InitBoneControllers();
8 years ago
pev->solid = SOLID_BBOX;
7 years ago
pev->movetype = MOVETYPE_TOSS;// so he'll fall to ground
pev->frame = 0;
8 years ago
ResetSequenceInfo();
7 years ago
pev->framerate = 0;
7 years ago
// Copy health
pev->max_health = pev->health;
pev->deadflag = DEAD_DEAD;
8 years ago
UTIL_SetSize( pev, g_vecZero, g_vecZero );
7 years ago
UTIL_SetOrigin( this, pev->origin );
// Setup health counters, etc.
BecomeDead();
9 years ago
SetThink( &CBaseMonster::CorpseFallThink );
SetNextThink( 0.5f );
7 years ago
}
//=========================================================
// BBoxIsFlat - check to see if the monster's bounding box
// is lying flat on a surface (traces from all four corners
// are same length.)
//=========================================================
8 years ago
BOOL CBaseMonster::BBoxFlat( void )
7 years ago
{
TraceResult tr;
Vector vecPoint;
float flXSize, flYSize;
float flLength;
float flLength2;
flXSize = pev->size.x / 2;
flYSize = pev->size.y / 2;
vecPoint.x = pev->origin.x + flXSize;
vecPoint.y = pev->origin.y + flYSize;
vecPoint.z = pev->origin.z;
8 years ago
UTIL_TraceLine( vecPoint, vecPoint - Vector( 0, 0, 100 ), ignore_monsters, ENT( pev ), &tr );
flLength = ( vecPoint - tr.vecEndPos ).Length();
7 years ago
vecPoint.x = pev->origin.x - flXSize;
vecPoint.y = pev->origin.y - flYSize;
8 years ago
UTIL_TraceLine( vecPoint, vecPoint - Vector( 0, 0, 100 ), ignore_monsters, ENT( pev ), &tr );
flLength2 = ( vecPoint - tr.vecEndPos ).Length();
if( flLength2 > flLength )
7 years ago
{
return FALSE;
}
flLength = flLength2;
vecPoint.x = pev->origin.x - flXSize;
vecPoint.y = pev->origin.y + flYSize;
8 years ago
UTIL_TraceLine ( vecPoint, vecPoint - Vector( 0, 0, 100 ), ignore_monsters, ENT( pev ), &tr );
flLength2 = ( vecPoint - tr.vecEndPos ).Length();
if( flLength2 > flLength )
7 years ago
{
return FALSE;
}
flLength = flLength2;
vecPoint.x = pev->origin.x + flXSize;
vecPoint.y = pev->origin.y - flYSize;
8 years ago
UTIL_TraceLine( vecPoint, vecPoint - Vector( 0, 0, 100 ), ignore_monsters, ENT( pev ), &tr );
flLength2 = ( vecPoint - tr.vecEndPos ).Length();
if( flLength2 > flLength )
7 years ago
{
return FALSE;
}
// flLength = flLength2;
7 years ago
return TRUE;
}
//=========================================================
// Get Enemy - tries to find the best suitable enemy for the monster.
//=========================================================
8 years ago
BOOL CBaseMonster::GetEnemy( void )
7 years ago
{
CBaseEntity *pNewEnemy;
8 years ago
if( HasConditions( bits_COND_SEE_HATE | bits_COND_SEE_DISLIKE | bits_COND_SEE_NEMESIS ) )
7 years ago
{
pNewEnemy = BestVisibleEnemy();
8 years ago
if( pNewEnemy != m_hEnemy && pNewEnemy != NULL )
7 years ago
{
// DO NOT mess with the monster's m_hEnemy pointer unless the schedule the monster is currently running will be interrupted
// by COND_NEW_ENEMY. This will eliminate the problem of monsters getting a new enemy while they are in a schedule that doesn't care,
// and then not realizing it by the time they get to a schedule that does. I don't feel this is a good permanent fix.
8 years ago
if( m_pSchedule )
7 years ago
{
8 years ago
if( m_pSchedule->iInterruptMask & bits_COND_NEW_ENEMY )
7 years ago
{
PushEnemy( m_hEnemy, m_vecEnemyLKP );
8 years ago
SetConditions( bits_COND_NEW_ENEMY );
7 years ago
m_hEnemy = pNewEnemy;
m_vecEnemyLKP = m_hEnemy->pev->origin;
}
// if the new enemy has an owner, take that one as well
8 years ago
if( pNewEnemy->pev->owner != NULL )
7 years ago
{
CBaseEntity *pOwner = GetMonsterPointer( pNewEnemy->pev->owner );
8 years ago
if( pOwner && ( pOwner->pev->flags & FL_MONSTER ) && IRelationship( pOwner ) != R_NO )
7 years ago
PushEnemy( pOwner, m_vecEnemyLKP );
}
}
}
}
// remember old enemies
if( m_hEnemy == 0 && PopEnemy() )
7 years ago
{
8 years ago
if( m_pSchedule )
7 years ago
{
8 years ago
if( m_pSchedule->iInterruptMask & bits_COND_NEW_ENEMY )
7 years ago
{
8 years ago
SetConditions( bits_COND_NEW_ENEMY );
7 years ago
}
}
}
if( m_hEnemy != 0 )
7 years ago
{
// monster has an enemy.
return TRUE;
}
return FALSE;// monster has no enemy
}
//=========================================================
// DropItem - dead monster drops named item
//=========================================================
CBaseEntity *CBaseMonster::DropItem( const char *pszItemName, const Vector &vecPos, const Vector &vecAng )
7 years ago
{
8 years ago
if( !pszItemName )
7 years ago
{
8 years ago
ALERT( at_console, "DropItem() - No item name!\n" );
7 years ago
return NULL;
}
CBaseEntity *pItem = CBaseEntity::Create( pszItemName, vecPos, vecAng, edict() );
8 years ago
if( pItem )
7 years ago
{
// do we want this behavior to be default?! (sjb)
pItem->pev->velocity = pev->velocity;
8 years ago
pItem->pev->avelocity = Vector( 0, RANDOM_FLOAT( 0, 100 ), 0 );
// Dropped items should never respawn (unless this rule changes in the future). - Solokiller
pItem->pev->spawnflags |= SF_NORESPAWN;
7 years ago
return pItem;
}
else
{
8 years ago
ALERT( at_console, "DropItem() - Didn't create!\n" );
7 years ago
return FALSE;
}
}
8 years ago
BOOL CBaseMonster::ShouldFadeOnDeath( void )
7 years ago
{
// if flagged to fade out or I have an owner (I came from a monster spawner)
8 years ago
if( ( pev->spawnflags & SF_MONSTER_FADECORPSE ) || !FNullEnt( pev->owner ) )
7 years ago
return TRUE;
return FALSE;
}
//LRC - an entity for monsters to shoot at.
#define SF_MONSTERTARGET_OFF 1
class CMonsterTarget : public CBaseEntity
{
public:
void Spawn( void );
void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
int Classify( void ) { return pev->frags; };
STATE GetState( void )
{
return pev->health?STATE_ON:STATE_OFF;
};
};
LINK_ENTITY_TO_CLASS( monster_target, CMonsterTarget );
void CMonsterTarget :: Spawn ( void )
{
if (pev->spawnflags & SF_MONSTERTARGET_OFF)
pev->health = 0;
else
pev->health = 1; // Don't ignore me, I'm not dead. I'm quite well really. I think I'll go for a walk...
SetBits (pev->flags, FL_MONSTER);
}
void CMonsterTarget::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if (ShouldToggle( useType ))
{
if (pev->health)
pev->health = 0;
else
pev->health = 1;
}
}