AIGuard.cpp 29 KB

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