AIGuard.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. /*
  2. ** Command & Conquer Generals Zero Hour(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. ////////////////////////////////////////////////////////////////////////////////
  19. // //
  20. // (c) 2001-2003 Electronic Arts Inc. //
  21. // //
  22. ////////////////////////////////////////////////////////////////////////////////
  23. // FILE: AIGuard.cpp
  24. /*---------------------------------------------------------------------------*/
  25. /* EA Pacific */
  26. /* Confidential Information */
  27. /* Copyright (C) 2001 - All Rights Reserved */
  28. /* DO NOT DISTRIBUTE */
  29. /*---------------------------------------------------------------------------*/
  30. /* Project: RTS3 */
  31. /* File name: AIGuard.cpp */
  32. /* Created: John K. McDonald, Jr., 3/29/2002 */
  33. /* Desc: // Set up guard states for AI */
  34. /* Revision History: */
  35. /* 3/29/2002 : Initial creation */
  36. /*---------------------------------------------------------------------------*/
  37. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  38. #include "Common/PerfTimer.h"
  39. #include "Common/Team.h"
  40. #include "Common/Xfer.h"
  41. #include "Common/ThingTemplate.h"
  42. #include "GameLogic/AI.h"
  43. #include "GameLogic/AIPathfind.h"
  44. #include "GameLogic/AIGuard.h"
  45. #include "GameLogic/Module/AIUpdate.h"
  46. #include "GameLogic/Module/BodyModule.h"
  47. #include "GameLogic/Module/CollideModule.h"
  48. #include "GameLogic/Object.h"
  49. #include "GameLogic/PartitionManager.h"
  50. #include "GameLogic/PolygonTrigger.h"
  51. const Real CLOSE_ENOUGH = (25.0f);
  52. #ifdef _INTERNAL
  53. // for occasional debugging...
  54. //#pragma optimize("", off)
  55. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  56. #endif
  57. static Bool hasAttackedMeAndICanReturnFire( State *thisState, void* /*userData*/ )
  58. {
  59. Object *obj = thisState->getMachineOwner();
  60. BodyModuleInterface *bmi = obj ? obj->getBodyModule() : NULL;
  61. if (!(obj && bmi)) {
  62. return FALSE;
  63. }
  64. if (bmi->getClearableLastAttacker() == INVALID_ID) {
  65. return FALSE;
  66. }
  67. // K. It appears we have a valid aggressor. Find it, and determine if we can attack it, etc.
  68. Object *target = TheGameLogic->findObjectByID(bmi->getClearableLastAttacker());
  69. bmi->clearLastAttacker();
  70. // We use the clearable last attacker because we should continue attacking the guy. But if he
  71. // stops attacking us, then we want our timer to kick us off of him and make us go attack
  72. // other units instead.
  73. if (!target) {
  74. return FALSE;
  75. }
  76. if (obj->getRelationship(target) != ENEMIES) {
  77. return FALSE;
  78. }
  79. // This is a quick test on the target. It will be duplicated in getAbleToAttackSpecificObject,
  80. // but the payoff is worth the duplication.
  81. if (target->isEffectivelyDead()) {
  82. return FALSE;
  83. }
  84. //@todo: Get this out of here. Move it into the declaration of calling this function, or figure
  85. // out some way to call it less often.
  86. if (!obj->isAbleToAttack()) {
  87. return FALSE;
  88. }
  89. CanAttackResult result = obj->getAbleToAttackSpecificObject(ATTACK_NEW_TARGET, target, CMD_FROM_AI);
  90. if( result == ATTACKRESULT_POSSIBLE || result == ATTACKRESULT_POSSIBLE_AFTER_MOVING )
  91. {
  92. return TRUE;
  93. }
  94. return FALSE;
  95. }
  96. //-- ExitConditions -------------------------------------------------------------------------------
  97. /**
  98. * This returns true if the conditions specified have been met, false otherwise.
  99. */
  100. Bool ExitConditions::shouldExit(const StateMachine* machine) const
  101. {
  102. if (!machine->getGoalObject())
  103. {
  104. if (m_conditionsToConsider & ATTACK_ExitIfNoUnitFound)
  105. {
  106. return true;
  107. }
  108. else
  109. {
  110. return false;
  111. }
  112. }
  113. if (m_conditionsToConsider & ATTACK_ExitIfExpiredDuration)
  114. {
  115. if (TheGameLogic->getFrame() >= m_attackGiveUpFrame)
  116. {
  117. return true;
  118. }
  119. }
  120. if (m_conditionsToConsider & ATTACK_ExitIfOutsideRadius)
  121. {
  122. Coord3D deltaAggressor;
  123. Coord3D objPos = *machine->getGoalObject()->getPosition();
  124. deltaAggressor.x = objPos.x - m_center.x;
  125. deltaAggressor.y = objPos.y - m_center.y;
  126. // deltaAggressor.z = objPos.z - m_center.z;
  127. deltaAggressor.z = 0; // BGC - when we search for a target we don't account for Z, so why should we here?
  128. // changing this fixed a crash where a GLARebelInfantry would be in GuardReturnState, find
  129. // a target that is within range, then not be able to attack because its actually out of range.
  130. // then it would look for a new target, get the same one, and proceed in an infinite recursive
  131. // loop that eventually blew the stack.
  132. if (deltaAggressor.lengthSqr() > m_radiusSqr)
  133. {
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. //-- AIGuardMachine -------------------------------------------------------------------------------
  140. //--------------------------------------------------------------------------------------
  141. AIGuardMachine::AIGuardMachine( Object *owner ) :
  142. StateMachine(owner, "AIGuardMachine"),
  143. m_targetToGuard(INVALID_ID),
  144. m_areaToGuard(NULL),
  145. m_nemesisToAttack(INVALID_ID),
  146. m_guardMode(GUARDMODE_NORMAL)
  147. {
  148. m_positionToGuard.zero();
  149. static const StateConditionInfo attackAggressors[] =
  150. {
  151. StateConditionInfo(hasAttackedMeAndICanReturnFire, AI_GUARD_ATTACK_AGGRESSOR, NULL),
  152. StateConditionInfo(NULL, NULL, NULL) // keep last
  153. };
  154. // order matters: first state is the default state.
  155. // srj sez: I made "return" the start state, so that if ordered to guard a position
  156. // that isn't the unit's current position, it moves to that position first.
  157. //Kris: Except that guard return is more like an attack move, and will acquire targets while moving there.
  158. //This breaks deployAI units because they have to completely unpack before realizing that there is a target in range.
  159. //So I'm making AI_GUARD_INNER the first state.
  160. defineState( AI_GUARD_INNER, newInstance(AIGuardInnerState)( this ), AI_GUARD_OUTER, AI_GUARD_OUTER, attackAggressors );
  161. defineState( AI_GUARD_RETURN, newInstance(AIGuardReturnState)( this ), AI_GUARD_IDLE, AI_GUARD_INNER, attackAggressors );
  162. defineState( AI_GUARD_IDLE, newInstance(AIGuardIdleState)( this ), AI_GUARD_INNER, AI_GUARD_RETURN, attackAggressors );
  163. defineState( AI_GUARD_OUTER, newInstance(AIGuardOuterState)( this ), AI_GUARD_GET_CRATE, AI_GUARD_GET_CRATE );
  164. defineState( AI_GUARD_GET_CRATE, newInstance(AIGuardPickUpCrateState)( this ), AI_GUARD_RETURN, AI_GUARD_RETURN );
  165. defineState( AI_GUARD_ATTACK_AGGRESSOR, newInstance(AIGuardAttackAggressorState)( this ), AI_GUARD_INNER, AI_GUARD_INNER );
  166. }
  167. //--------------------------------------------------------------------------------------
  168. AIGuardMachine::~AIGuardMachine()
  169. {
  170. }
  171. //--------------------------------------------------------------------------------------
  172. /*static*/ Real AIGuardMachine::getStdGuardRange(const Object* obj)
  173. {
  174. Real visionRange = TheAI->getAdjustedVisionRangeForObject(obj,
  175. AI_VISIONFACTOR_OWNERTYPE | AI_VISIONFACTOR_MOOD | AI_VISIONFACTOR_GUARDINNER);
  176. return visionRange;
  177. }
  178. //--------------------------------------------------------------------------------------
  179. Bool AIGuardMachine::lookForInnerTarget(void)
  180. {
  181. Object* owner = getOwner();
  182. if (!owner->isAbleToAttack())
  183. {
  184. return false; // my, that was easy
  185. }
  186. // Check if team auto targets same victim.
  187. Object *teamVictim = NULL;
  188. if (owner->getTeam()->getPrototype()->getTemplateInfo()->m_attackCommonTarget)
  189. {
  190. teamVictim = owner->getTeam()->getTeamTargetObject();
  191. if (teamVictim)
  192. {
  193. setNemesisID(teamVictim->getID());
  194. return true; // Transitions to AIGuardInnerState.
  195. }
  196. }
  197. Object* targetToGuard = findTargetToGuardByID();
  198. Coord3D pos = targetToGuard ? *targetToGuard->getPosition() : *getPositionToGuard();
  199. const PolygonTrigger* area = getAreaToGuard();
  200. PartitionFilterRelationship f1(owner, PartitionFilterRelationship::ALLOW_ENEMIES);
  201. PartitionFilterPossibleToAttack f2(ATTACK_NEW_TARGET, owner, CMD_FROM_AI);
  202. PartitionFilterSameMapStatus filterMapStatus(owner);
  203. PartitionFilterPolygonTrigger f3(area);
  204. PartitionFilterIsFlying f4;
  205. PartitionFilterRelationship f5(owner, PartitionFilterRelationship::ALLOW_NEUTRAL);
  206. PartitionFilterPossibleToEnter f6(owner, CMD_FROM_AI);
  207. PartitionFilterPossibleToHijack f7(owner, CMD_FROM_AI);
  208. PartitionFilter *filters[16];
  209. Int count = 0;
  210. // Enter Guard state
  211. if (owner->getTemplate()->isEnterGuard())
  212. {
  213. filters[count++] = &f6;
  214. // Hijack Guard state
  215. if (owner->getTemplate()->isHijackGuard())
  216. {
  217. filters[count++] = &f1;
  218. filters[count++] = &f7;
  219. }
  220. else
  221. {
  222. filters[count++] = &f5;
  223. }
  224. }
  225. // Attack Guard state
  226. else
  227. {
  228. filters[count++] = &f1;
  229. filters[count++] = &f2;
  230. }
  231. filters[count++] = &filterMapStatus;
  232. Real visionRange = AIGuardMachine::getStdGuardRange(owner);
  233. if (area)
  234. {
  235. UnsignedInt checkFrame = TheGameLogic->getFrameObjectsChangedTriggerAreas()+TheAI->getAiData()->m_guardEnemyScanRate;
  236. if (TheGameLogic->getFrame()>checkFrame) {
  237. return false;
  238. }
  239. filters[count++] = &f3;
  240. visionRange = area->getRadius();
  241. area->getCenterPoint(&pos);
  242. }
  243. if (getGuardMode() == GUARDMODE_GUARD_FLYING_UNITS_ONLY)
  244. {
  245. // only consider flying targets
  246. filters[count++] = &f4;
  247. }
  248. filters[count++] = NULL;
  249. // SimpleObjectIterator* iter = ThePartitionManager->iterateObjectsInRange(
  250. // &pos, visionRange, FROM_CENTER_2D, filters, ITER_SORTED_NEAR_TO_FAR);
  251. // MemoryPoolObjectHolder hold(iter);
  252. // Object* target = iter->first();
  253. //
  254. // srj sez: the above code is stupid and slow. since we only want the closest object,
  255. // just ask for that; the above has to find ALL objects in range, but we ignore all
  256. // but the first (closest).
  257. //
  258. Object* target = ThePartitionManager->getClosestObject(&pos, visionRange, FROM_CENTER_2D, filters);
  259. if (target)
  260. {
  261. setNemesisID(target->getID());
  262. return true; // Transitions to AIGuardInnerState.
  263. }
  264. else
  265. {
  266. return false;
  267. }
  268. }
  269. // ------------------------------------------------------------------------------------------------
  270. /** CRC */
  271. // ------------------------------------------------------------------------------------------------
  272. void AIGuardMachine::crc( Xfer *xfer )
  273. {
  274. } // end crc
  275. // ------------------------------------------------------------------------------------------------
  276. /** Xfer Method */
  277. // ------------------------------------------------------------------------------------------------
  278. void AIGuardMachine::xfer( Xfer *xfer )
  279. {
  280. // version
  281. XferVersion currentVersion = 2;
  282. XferVersion version = currentVersion;
  283. xfer->xferVersion( &version, currentVersion );
  284. if (version>=2) {
  285. StateMachine::xfer(xfer); // Forgot this in initial implementation. jba.
  286. }
  287. xfer->xferObjectID(&m_targetToGuard);
  288. xfer->xferObjectID(&m_nemesisToAttack);
  289. xfer->xferCoord3D(&m_positionToGuard);
  290. AsciiString triggerName;
  291. if (m_areaToGuard) triggerName = m_areaToGuard->getTriggerName();
  292. xfer->xferAsciiString(&triggerName);
  293. if (xfer->getXferMode() == XFER_LOAD)
  294. {
  295. if (triggerName.isNotEmpty()) {
  296. m_areaToGuard = TheTerrainLogic->getTriggerAreaByName(triggerName);
  297. }
  298. }
  299. } // end xfer
  300. // ------------------------------------------------------------------------------------------------
  301. /** Load post process */
  302. // ------------------------------------------------------------------------------------------------
  303. void AIGuardMachine::loadPostProcess( void )
  304. {
  305. } // end loadPostProcess
  306. //-- AIGuardInnerState ----------------------------------------------------------------------------
  307. // ------------------------------------------------------------------------------------------------
  308. /** CRC */
  309. // ------------------------------------------------------------------------------------------------
  310. void AIGuardInnerState::crc( Xfer *xfer )
  311. {
  312. } // end crc
  313. // ------------------------------------------------------------------------------------------------
  314. /** Xfer Method */
  315. // ------------------------------------------------------------------------------------------------
  316. void AIGuardInnerState::xfer( Xfer *xfer )
  317. {
  318. // version
  319. XferVersion currentVersion = 1;
  320. XferVersion version = currentVersion;
  321. xfer->xferVersion( &version, currentVersion );
  322. } // end xfer
  323. // ------------------------------------------------------------------------------------------------
  324. /** Load post process */
  325. // ------------------------------------------------------------------------------------------------
  326. void AIGuardInnerState::loadPostProcess( void )
  327. {
  328. onEnter();
  329. } // end loadPostProcess
  330. //--------------------------------------------------------------------------------------
  331. StateReturnType AIGuardInnerState::onEnter( void )
  332. {
  333. // See if we try to enter the target
  334. if (getMachineOwner()->getTemplate()->isEnterGuard())
  335. {
  336. Object* nemesis = TheGameLogic->findObjectByID(getGuardMachine()->getNemesisID()) ;
  337. if (nemesis == NULL)
  338. {
  339. DEBUG_LOG(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
  340. return STATE_SUCCESS;
  341. }
  342. m_enterState = newInstance(AIEnterState)(getMachine());
  343. m_enterState->getMachine()->setGoalObject(nemesis);
  344. StateReturnType returnVal = m_enterState->onEnter();
  345. if (returnVal == STATE_CONTINUE) {
  346. return STATE_CONTINUE;
  347. }
  348. }
  349. // Or try to destroy the target
  350. else
  351. {
  352. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  353. Coord3D pos = targetToGuard ? *targetToGuard->getPosition() : *getGuardMachine()->getPositionToGuard();
  354. Object* nemesis = TheGameLogic->findObjectByID(getGuardMachine()->getNemesisID()) ;
  355. if (nemesis == NULL)
  356. {
  357. DEBUG_LOG(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
  358. return STATE_SUCCESS;
  359. }
  360. m_exitConditions.m_center = pos;
  361. m_exitConditions.m_radiusSqr = sqr(AIGuardMachine::getStdGuardRange(getMachineOwner()));
  362. m_exitConditions.m_conditionsToConsider = (ExitConditions::ATTACK_ExitIfOutsideRadius |
  363. ExitConditions::ATTACK_ExitIfNoUnitFound);
  364. m_attackState = newInstance(AIAttackState)(getMachine(), false, true, false, &m_exitConditions);
  365. m_attackState->getMachine()->setGoalObject(nemesis);
  366. StateReturnType returnVal = m_attackState->onEnter();
  367. if (returnVal == STATE_CONTINUE) {
  368. return STATE_CONTINUE;
  369. }
  370. }
  371. // if we had no one to attack, we were successful, so go to the next state.
  372. return STATE_SUCCESS;
  373. }
  374. //--------------------------------------------------------------------------------------
  375. StateReturnType AIGuardInnerState::update( void )
  376. {
  377. if (m_attackState)
  378. {
  379. // if the position has moved (IE we're guarding an object), move with it.
  380. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  381. if (targetToGuard)
  382. {
  383. m_exitConditions.m_center = *targetToGuard->getPosition();
  384. }
  385. return m_attackState->update();
  386. }
  387. else if (m_enterState)
  388. {
  389. return m_enterState->update();
  390. }
  391. return STATE_SUCCESS;
  392. }
  393. //--------------------------------------------------------------------------------------
  394. void AIGuardInnerState::onExit( StateExitType status )
  395. {
  396. Object *obj = getMachineOwner();
  397. if (m_attackState)
  398. {
  399. m_attackState->onExit(status);
  400. m_attackState->deleteInstance();
  401. m_attackState = NULL;
  402. }
  403. else if (m_enterState)
  404. {
  405. m_enterState->onExit(status);
  406. m_enterState->deleteInstance();
  407. m_enterState = NULL;
  408. }
  409. if (obj->getTeam())
  410. {
  411. obj->getTeam()->setTeamTargetObject(NULL); // clear the target.
  412. }
  413. }
  414. //-- AIGuardOuterState ----------------------------------------------------------------------------
  415. // ------------------------------------------------------------------------------------------------
  416. /** CRC */
  417. // ------------------------------------------------------------------------------------------------
  418. void AIGuardOuterState::crc( Xfer *xfer )
  419. {
  420. } // end crc
  421. // ------------------------------------------------------------------------------------------------
  422. /** Xfer Method */
  423. // ------------------------------------------------------------------------------------------------
  424. void AIGuardOuterState::xfer( Xfer *xfer )
  425. {
  426. // version
  427. XferVersion currentVersion = 1;
  428. XferVersion version = currentVersion;
  429. xfer->xferVersion( &version, currentVersion );
  430. } // end xfer
  431. // ------------------------------------------------------------------------------------------------
  432. /** Load post process */
  433. // ------------------------------------------------------------------------------------------------
  434. void AIGuardOuterState::loadPostProcess( void )
  435. { AIGuardOuterState
  436. onEnter();
  437. } // end loadPostProcess
  438. //--------------------------------------------------------------------------------------
  439. StateReturnType AIGuardOuterState::onEnter( void )
  440. {
  441. if (getGuardMachine()->getGuardMode() == GUARDMODE_GUARD_WITHOUT_PURSUIT)
  442. {
  443. // "patrol" mode does not follow targets outside the guard area.
  444. return STATE_SUCCESS;
  445. }
  446. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  447. Coord3D pos = targetToGuard ? *targetToGuard->getPosition() : *getGuardMachine()->getPositionToGuard();
  448. Object* nemesis = TheGameLogic->findObjectByID(getGuardMachine()->getNemesisID()) ;
  449. if (nemesis == NULL)
  450. {
  451. DEBUG_LOG(("Unexpected NULL nemesis in AIGuardInnerState.\n"));
  452. return STATE_SUCCESS;
  453. }
  454. Object *obj = getMachineOwner();
  455. Real range = TheAI->getAdjustedVisionRangeForObject(obj, AI_VISIONFACTOR_OWNERTYPE | AI_VISIONFACTOR_MOOD);
  456. const PolygonTrigger *area = getGuardMachine()->getAreaToGuard();
  457. if (area)
  458. {
  459. if (range < area->getRadius())
  460. range = area->getRadius();
  461. area->getCenterPoint(&pos);
  462. }
  463. m_exitConditions.m_center = pos;
  464. m_exitConditions.m_radiusSqr = sqr(range);
  465. m_exitConditions.m_attackGiveUpFrame = TheGameLogic->getFrame() + TheAI->getAiData()->m_guardChaseUnitFrames;
  466. m_exitConditions.m_conditionsToConsider = (ExitConditions::ATTACK_ExitIfExpiredDuration |
  467. ExitConditions::ATTACK_ExitIfOutsideRadius |
  468. ExitConditions::ATTACK_ExitIfNoUnitFound);
  469. m_attackState = newInstance(AIAttackState)(getMachine(), false, true, false, &m_exitConditions);
  470. m_attackState->getMachine()->setGoalObject(nemesis);
  471. StateReturnType returnVal = m_attackState->onEnter();
  472. if (returnVal == STATE_CONTINUE) {
  473. return STATE_CONTINUE;
  474. }
  475. // if we had no one to attack, we were successful, so go to the next state.
  476. return STATE_SUCCESS;
  477. }
  478. //--------------------------------------------------------------------------------------
  479. StateReturnType AIGuardOuterState::update( void )
  480. {
  481. if (m_attackState==NULL) return STATE_SUCCESS;
  482. // if the position has moved (IE we're guarding an object), move with it.
  483. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  484. if (targetToGuard)
  485. {
  486. m_exitConditions.m_center = *targetToGuard->getPosition();
  487. }
  488. Object* goalObj = m_attackState->getMachineGoalObject();
  489. if (goalObj)
  490. {
  491. Coord3D deltaAggr;
  492. deltaAggr.x = m_exitConditions.m_center.x - goalObj->getPosition()->x;
  493. deltaAggr.y = m_exitConditions.m_center.y - goalObj->getPosition()->y;
  494. deltaAggr.z = m_exitConditions.m_center.z - goalObj->getPosition()->z;
  495. Real visionSqr = sqr(AIGuardMachine::getStdGuardRange(getMachineOwner()));
  496. if (deltaAggr.lengthSqr() <= visionSqr)
  497. {
  498. // reset the counter
  499. m_exitConditions.m_attackGiveUpFrame = TheGameLogic->getFrame() + TheAI->getAiData()->m_guardChaseUnitFrames;
  500. }
  501. }
  502. return m_attackState->update();
  503. }
  504. //--------------------------------------------------------------------------------------
  505. void AIGuardOuterState::onExit( StateExitType status )
  506. {
  507. if (m_attackState)
  508. {
  509. m_attackState->onExit(status);
  510. m_attackState->deleteInstance();
  511. m_attackState = NULL;
  512. }
  513. }
  514. //-- AIGuardReturnState ----------------------------------------------------------------------------
  515. // ------------------------------------------------------------------------------------------------
  516. /** CRC */
  517. // ------------------------------------------------------------------------------------------------
  518. void AIGuardReturnState::crc( Xfer *xfer )
  519. {
  520. } // end crc
  521. // ------------------------------------------------------------------------------------------------
  522. /** Xfer Method */
  523. // ------------------------------------------------------------------------------------------------
  524. void AIGuardReturnState::xfer( Xfer *xfer )
  525. {
  526. // version
  527. XferVersion currentVersion = 1;
  528. XferVersion version = currentVersion;
  529. xfer->xferVersion( &version, currentVersion );
  530. xfer->xferUnsignedInt(&m_nextReturnScanTime);
  531. } // end xfer
  532. // ------------------------------------------------------------------------------------------------
  533. /** Load post process */
  534. // ------------------------------------------------------------------------------------------------
  535. void AIGuardReturnState::loadPostProcess( void )
  536. {
  537. } // end loadPostProcess
  538. //--------------------------------------------------------------------------------------
  539. StateReturnType AIGuardReturnState::onEnter( void )
  540. {
  541. UnsignedInt now = TheGameLogic->getFrame();
  542. m_nextReturnScanTime = now + GameLogicRandomValue(0, TheAI->getAiData()->m_guardEnemyReturnScanRate);
  543. // no, no, no, don't do this in onEnter, unless you like really slow maps. (srj)
  544. // if (getGuardMachine()->lookForInnerTarget())
  545. // return STATE_FAILURE; // early termination because we found a target.
  546. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  547. m_goalPosition = targetToGuard ? *targetToGuard->getPosition() : *getGuardMachine()->getPositionToGuard();
  548. const PolygonTrigger *area = getGuardMachine()->getAreaToGuard();
  549. if (area)
  550. {
  551. area->getCenterPoint(&m_goalPosition);
  552. }
  553. AIUpdateInterface *ai = getMachineOwner()->getAIUpdateInterface();
  554. if (ai && ai->isDoingGroundMovement())
  555. {
  556. TheAI->pathfinder()->adjustDestination(getMachineOwner(), ai->getLocomotorSet(), &m_goalPosition);
  557. }
  558. setAdjustsDestination(true);
  559. return AIInternalMoveToState::onEnter();
  560. }
  561. //--------------------------------------------------------------------------------------
  562. StateReturnType AIGuardReturnState::update( void )
  563. {
  564. UnsignedInt now = TheGameLogic->getFrame();
  565. if (now >= m_nextReturnScanTime)
  566. {
  567. m_nextReturnScanTime = now + TheAI->getAiData()->m_guardEnemyReturnScanRate;
  568. if (getGuardMachine()->lookForInnerTarget())
  569. return STATE_FAILURE; // early termination because we found a target.
  570. }
  571. // Just let the return movement finish.
  572. return AIInternalMoveToState::update();
  573. }
  574. //--------------------------------------------------------------------------------------
  575. void AIGuardReturnState::onExit( StateExitType status )
  576. {
  577. AIInternalMoveToState::onExit( status );
  578. }
  579. //-- AIGuardIdleState ----------------------------------------------------------------------------
  580. // ------------------------------------------------------------------------------------------------
  581. /** CRC */
  582. // ------------------------------------------------------------------------------------------------
  583. void AIGuardIdleState::crc( Xfer *xfer )
  584. {
  585. } // end crc
  586. // ------------------------------------------------------------------------------------------------
  587. /** Xfer Method */
  588. // ------------------------------------------------------------------------------------------------
  589. void AIGuardIdleState::xfer( Xfer *xfer )
  590. {
  591. // version
  592. XferVersion currentVersion = 1;
  593. XferVersion version = currentVersion;
  594. xfer->xferVersion( &version, currentVersion );
  595. xfer->xferUnsignedInt(&m_nextEnemyScanTime);
  596. } // end xfer
  597. // ------------------------------------------------------------------------------------------------
  598. /** Load post process */
  599. // ------------------------------------------------------------------------------------------------
  600. void AIGuardIdleState::loadPostProcess( void )
  601. {
  602. } // end loadPostProcess
  603. //--------------------------------------------------------------------------------------
  604. StateReturnType AIGuardIdleState::onEnter( void )
  605. {
  606. // first time thru, use a random amount so that everyone doesn't scan on the same frame,
  607. // to avoid "spikes".
  608. UnsignedInt now = TheGameLogic->getFrame();
  609. m_nextEnemyScanTime = now + GameLogicRandomValue(0, TheAI->getAiData()->m_guardEnemyScanRate);
  610. return STATE_CONTINUE;
  611. }
  612. //--------------------------------------------------------------------------------------
  613. StateReturnType AIGuardIdleState::update( void )
  614. {
  615. //DEBUG_LOG(("AIGuardIdleState frame %d: %08lx\n",TheGameLogic->getFrame(),getMachineOwner()));
  616. UnsignedInt now = TheGameLogic->getFrame();
  617. if (now < m_nextEnemyScanTime)
  618. return STATE_SLEEP(m_nextEnemyScanTime - now);
  619. m_nextEnemyScanTime = now + TheAI->getAiData()->m_guardEnemyScanRate;
  620. #ifdef STATE_MACHINE_DEBUG
  621. //getMachine()->setDebugOutput(true);
  622. #endif
  623. Object *owner = getMachineOwner();
  624. AIUpdateInterface *ai = owner->getAIUpdateInterface();
  625. // Check to see if we have created a crate we need to pick up.
  626. if (ai->getCrateID() != INVALID_ID)
  627. {
  628. getMachine()->setState(AI_GUARD_GET_CRATE);
  629. return STATE_SLEEP(m_nextEnemyScanTime - now);
  630. }
  631. // if anyone is in the inner area, return success.
  632. if (getGuardMachine()->lookForInnerTarget())
  633. {
  634. return STATE_SUCCESS; // Transitions to AIGuardInnerState.
  635. }
  636. // See if the object we are guarding moved.
  637. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  638. if (targetToGuard)
  639. {
  640. Coord3D pos = *targetToGuard->getPosition();
  641. Real delta = m_guardeePos.x-pos.x;
  642. if (delta*delta > 4*PATHFIND_CELL_SIZE_F*PATHFIND_CELL_SIZE_F) {
  643. m_guardeePos = pos;
  644. return STATE_FAILURE; // goes to AIGuardReturnState.
  645. }
  646. delta = m_guardeePos.y-pos.y;
  647. if (delta*delta > 4*PATHFIND_CELL_SIZE_F*PATHFIND_CELL_SIZE_F) {
  648. m_guardeePos = pos;
  649. return STATE_FAILURE; // goes to AIGuardReturnState.
  650. }
  651. }
  652. return STATE_SLEEP(m_nextEnemyScanTime - now);
  653. }
  654. //--------------------------------------------------------------------------------------
  655. void AIGuardIdleState::onExit( StateExitType status )
  656. {
  657. }
  658. //-- AIGuardPickUpCrateState ----------------------------------------------------------------------
  659. //-------------------------------------------------------------------------------------------------
  660. AIGuardPickUpCrateState::AIGuardPickUpCrateState( StateMachine *machine ) : AIPickUpCrateState(machine)
  661. {
  662. #ifdef STATE_MACHINE_DEBUG
  663. setName("AIGuardPickUpCrateState");
  664. #endif
  665. }
  666. //--------------------------------------------------------------------------------------
  667. StateReturnType AIGuardPickUpCrateState::onEnter( void )
  668. {
  669. Object *owner = getMachineOwner();
  670. AIUpdateInterface *ai = owner->getAIUpdateInterface();
  671. // Check to see if we have created a crate we need to pick up.
  672. Object* crate = ai->checkForCrateToPickup();
  673. if (crate)
  674. {
  675. getMachine()->setGoalObject(crate);
  676. return AIPickUpCrateState::onEnter();
  677. }
  678. return STATE_SUCCESS; // no crate, so we're done.
  679. }
  680. //--------------------------------------------------------------------------------------
  681. StateReturnType AIGuardPickUpCrateState::update( void )
  682. {
  683. return AIPickUpCrateState::update();
  684. }
  685. //--------------------------------------------------------------------------------------
  686. void AIGuardPickUpCrateState::onExit( StateExitType status )
  687. {
  688. }
  689. //-- AIGuardAttackAggressorState ------------------------------------------------------------------
  690. //-------------------------------------------------------------------------------------------------
  691. AIGuardAttackAggressorState::AIGuardAttackAggressorState( StateMachine *machine ) :
  692. State( machine, "AIGuardAttackAggressorState" )
  693. {
  694. m_attackState = NULL;
  695. }
  696. //-------------------------------------------------------------------------------------------------
  697. StateReturnType AIGuardAttackAggressorState::onEnter( void )
  698. {
  699. Object *obj = getMachineOwner();
  700. ObjectID nemID = INVALID_ID;
  701. if (obj->getBodyModule() && obj->getBodyModule()->getLastDamageInfo()->in.m_sourceID) {
  702. nemID = obj->getBodyModule()->getLastDamageInfo()->in.m_sourceID;
  703. getGuardMachine()->setNemesisID(nemID);
  704. }
  705. Object *nemesis = TheGameLogic->findObjectByID(getGuardMachine()->getNemesisID());
  706. if (nemesis == NULL)
  707. {
  708. DEBUG_LOG(("Unexpected NULL nemesis in AIGuardAttackAggressorState.\n"));
  709. return STATE_SUCCESS;
  710. }
  711. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  712. Coord3D pos = targetToGuard ? *targetToGuard->getPosition() : *getGuardMachine()->getPositionToGuard();
  713. //Don't allow guarding units to leave their guard radius!
  714. m_exitConditions.m_center = pos;
  715. m_exitConditions.m_radiusSqr = sqr(AIGuardMachine::getStdGuardRange(getMachineOwner()));
  716. m_exitConditions.m_attackGiveUpFrame = TheGameLogic->getFrame() + TheAI->getAiData()->m_guardChaseUnitFrames;
  717. m_exitConditions.m_conditionsToConsider = (ExitConditions::ATTACK_ExitIfExpiredDuration |
  718. ExitConditions::ATTACK_ExitIfNoUnitFound |
  719. ExitConditions::ATTACK_ExitIfOutsideRadius );
  720. m_attackState = newInstance(AIAttackState)(getMachine(), true, true, false, &m_exitConditions);
  721. m_attackState->getMachine()->setGoalObject(nemesis);
  722. StateReturnType returnVal = m_attackState->onEnter();
  723. if (returnVal == STATE_CONTINUE) {
  724. return STATE_CONTINUE;
  725. }
  726. // if we had no one to attack, we were successful, so go to the next state.
  727. return STATE_SUCCESS;
  728. }
  729. //-------------------------------------------------------------------------------------------------
  730. StateReturnType AIGuardAttackAggressorState::update( void )
  731. {
  732. if (m_attackState==NULL) return STATE_SUCCESS;
  733. // if the position has moved (IE we're guarding an object), move with it.
  734. Object* targetToGuard = getGuardMachine()->findTargetToGuardByID();
  735. if (targetToGuard)
  736. {
  737. m_exitConditions.m_center = *targetToGuard->getPosition();
  738. }
  739. return m_attackState->update();
  740. }
  741. //-------------------------------------------------------------------------------------------------
  742. void AIGuardAttackAggressorState::onExit( StateExitType status )
  743. {
  744. Object *obj = getMachineOwner();
  745. if (m_attackState)
  746. {
  747. m_attackState->onExit(status);
  748. m_attackState->deleteInstance();
  749. m_attackState = NULL;
  750. }
  751. if (obj->getTeam())
  752. {
  753. obj->getTeam()->setTeamTargetObject(NULL); // clear the target.
  754. }
  755. }
  756. //-------------------------------------------------------------------------------------------------
  757. void AIGuardAttackAggressorState::crc( Xfer *xfer )
  758. {
  759. }
  760. //-------------------------------------------------------------------------------------------------
  761. void AIGuardAttackAggressorState::xfer( Xfer *xfer )
  762. {
  763. // version
  764. XferVersion currentVersion = 1;
  765. XferVersion version = currentVersion;
  766. xfer->xferVersion( &version, currentVersion );
  767. }
  768. //-------------------------------------------------------------------------------------------------
  769. void AIGuardAttackAggressorState::loadPostProcess()
  770. {
  771. onEnter();
  772. }