aiTurretShape.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "T3D/turret/aiTurretShape.h"
  23. #include "console/console.h"
  24. #include "console/consoleTypes.h"
  25. #include "console/engineAPI.h"
  26. #include "core/stream/bitStream.h"
  27. #include "math/mMath.h"
  28. #include "math/mathIO.h"
  29. #include "math/mathUtils.h"
  30. #include "gfx/gfxDrawUtil.h"
  31. #include "ts/tsShapeInstance.h"
  32. #include "math/mRandom.h"
  33. static U32 sScanTypeMask = PlayerObjectType |
  34. VehicleObjectType;
  35. static U32 sAimTypeMask = TerrainObjectType |
  36. WaterObjectType |
  37. PlayerObjectType |
  38. StaticShapeObjectType |
  39. VehicleObjectType |
  40. ItemObjectType;
  41. //----------------------------------------------------------------------------
  42. AITurretShapeData::StateData::StateData()
  43. {
  44. name = 0;
  45. transition.rest[0] = transition.rest[1] = -1;
  46. transition.target[0] = transition.target[1] = -1;
  47. transition.activated[0] = transition.activated[1] = -1;
  48. transition.timeout = -1;
  49. waitForTimeout = true;
  50. timeoutValue = 0;
  51. fire = false;
  52. scan = false;
  53. script = 0;
  54. scaleAnimation = false;
  55. direction = false;
  56. sequence = -1;
  57. }
  58. static AITurretShapeData::StateData gDefaultStateData;
  59. //----------------------------------------------------------------------------
  60. IMPLEMENT_CO_DATABLOCK_V1(AITurretShapeData);
  61. ConsoleDocClass( AITurretShapeData,
  62. "@brief Defines properties for an AITurretShape object.\n\n"
  63. "@see AITurretShape\n"
  64. "@see TurretShapeData\n"
  65. "@ingroup gameObjects\n"
  66. );
  67. AITurretShapeData::AITurretShapeData()
  68. {
  69. maxScanHeading = 90;
  70. maxScanPitch = 90;
  71. maxScanDistance = 20;
  72. // Do a full scan every three ticks
  73. scanTickFrequency = 3;
  74. // Randomly add 0 to 1 ticks to the scan frequency as
  75. // chosen every scan period.
  76. scanTickFrequencyVariance = 1;
  77. trackLostTargetTime = 0;
  78. scanNode = -1;
  79. aimNode = -1;
  80. maxWeaponRange = 100;
  81. weaponLeadVelocity = 0;
  82. for (S32 i = 0; i < MaxStates; i++) {
  83. stateName[i] = 0;
  84. stateTransitionAtRest[i] = 0;
  85. stateTransitionNotAtRest[i] = 0;
  86. stateTransitionTarget[i] = 0;
  87. stateTransitionNoTarget[i] = 0;
  88. stateTransitionActivated[i] = 0;
  89. stateTransitionDeactivated[i] = 0;
  90. stateTransitionTimeout[i] = 0;
  91. stateWaitForTimeout[i] = true;
  92. stateTimeoutValue[i] = 0;
  93. stateFire[i] = false;
  94. stateScan[i] = false;
  95. stateScaleAnimation[i] = true;
  96. stateDirection[i] = true;
  97. stateSequence[i] = 0;
  98. stateScript[i] = 0;
  99. }
  100. isAnimated = false;
  101. statesLoaded = false;
  102. }
  103. void AITurretShapeData::initPersistFields()
  104. {
  105. addField("maxScanHeading", TypeF32, Offset(maxScanHeading, AITurretShapeData),
  106. "@brief Maximum number of degrees to scan left and right.\n\n"
  107. "@note Maximum scan heading is 90 degrees.\n");
  108. addField("maxScanPitch", TypeF32, Offset(maxScanPitch, AITurretShapeData),
  109. "@brief Maximum number of degrees to scan up and down.\n\n"
  110. "@note Maximum scan pitch is 90 degrees.\n");
  111. addField("maxScanDistance", TypeF32, Offset(maxScanDistance, AITurretShapeData),
  112. "@brief Maximum distance to scan.\n\n"
  113. "When combined with maxScanHeading and maxScanPitch this forms a 3D scanning wedge used to initially "
  114. "locate a target.\n");
  115. addField("scanTickFrequency", TypeS32, Offset(scanTickFrequency, AITurretShapeData),
  116. "@brief How often should we perform a full scan when looking for a target.\n\n"
  117. "Expressed as the number of ticks between full scans, but no less than 1.\n");
  118. addField("scanTickFrequencyVariance", TypeS32, Offset(scanTickFrequencyVariance, AITurretShapeData),
  119. "@brief Random amount that should be added to the scan tick frequency each scan period.\n\n"
  120. "Expressed as the number of ticks to randomly add, but no less than zero.\n");
  121. addField("trackLostTargetTime", TypeF32, Offset(trackLostTargetTime, AITurretShapeData),
  122. "@brief How long after the turret has lost the target should it still track it.\n\n"
  123. "Expressed in seconds.\n");
  124. addField("maxWeaponRange", TypeF32, Offset(maxWeaponRange, AITurretShapeData),
  125. "@brief Maximum distance that the weapon will fire upon a target.\n\n");
  126. addField("weaponLeadVelocity", TypeF32, Offset(weaponLeadVelocity, AITurretShapeData),
  127. "@brief Velocity used to lead target.\n\n"
  128. "If value <= 0, don't lead target.\n");
  129. // State arrays
  130. addArray( "States", MaxStates );
  131. addField( "stateName", TypeCaseString, Offset(stateName, AITurretShapeData), MaxStates,
  132. "Name of this state." );
  133. addField( "stateTransitionOnAtRest", TypeString, Offset(stateTransitionAtRest, AITurretShapeData), MaxStates,
  134. "Name of the state to transition to when the turret is at rest (static).");
  135. addField( "stateTransitionOnNotAtRest", TypeString, Offset(stateTransitionNotAtRest, AITurretShapeData), MaxStates,
  136. "Name of the state to transition to when the turret is not at rest (not static).");
  137. addField( "stateTransitionOnTarget", TypeString, Offset(stateTransitionTarget, AITurretShapeData), MaxStates,
  138. "Name of the state to transition to when the turret gains a target." );
  139. addField( "stateTransitionOnNoTarget", TypeString, Offset(stateTransitionNoTarget, AITurretShapeData), MaxStates,
  140. "Name of the state to transition to when the turret loses a target." );
  141. addField( "stateTransitionOnActivated", TypeString, Offset(stateTransitionActivated, AITurretShapeData), MaxStates,
  142. "Name of the state to transition to when the turret goes from deactivated to activated.");
  143. addField( "stateTransitionOnDeactivated", TypeString, Offset(stateTransitionDeactivated, AITurretShapeData), MaxStates,
  144. "Name of the state to transition to when the turret goes from activated to deactivated");
  145. addField( "stateTransitionOnTimeout", TypeString, Offset(stateTransitionTimeout, AITurretShapeData), MaxStates,
  146. "Name of the state to transition to when we have been in this state "
  147. "for stateTimeoutValue seconds." );
  148. addField( "stateTimeoutValue", TypeF32, Offset(stateTimeoutValue, AITurretShapeData), MaxStates,
  149. "Time in seconds to wait before transitioning to stateTransitionOnTimeout." );
  150. addField( "stateWaitForTimeout", TypeBool, Offset(stateWaitForTimeout, AITurretShapeData), MaxStates,
  151. "If false, this state ignores stateTimeoutValue and transitions "
  152. "immediately if other transition conditions are met." );
  153. addField( "stateFire", TypeBool, Offset(stateFire, AITurretShapeData), MaxStates,
  154. "The first state with this set to true is the state entered by the "
  155. "client when it receives the 'fire' event." );
  156. addField( "stateScan", TypeBool, Offset(stateScan, AITurretShapeData), MaxStates,
  157. "Indicates the turret should perform a continuous scan looking for targets." );
  158. addField( "stateDirection", TypeBool, Offset(stateDirection, AITurretShapeData), MaxStates,
  159. "@brief Direction of the animation to play in this state.\n\n"
  160. "True is forward, false is backward." );
  161. addField( "stateSequence", TypeString, Offset(stateSequence, AITurretShapeData), MaxStates,
  162. "Name of the sequence to play on entry to this state." );
  163. addField( "stateScaleAnimation", TypeBool, Offset(stateScaleAnimation, AITurretShapeData), MaxStates,
  164. "If true, the timeScale of the stateSequence animation will be adjusted "
  165. "such that the sequence plays for stateTimeoutValue seconds. " );
  166. addField( "stateScript", TypeCaseString, Offset(stateScript, AITurretShapeData), MaxStates,
  167. "@brief Method to execute on entering this state.\n\n"
  168. "Scoped to AITurretShapeData.");
  169. endArray( "States" );
  170. Parent::initPersistFields();
  171. }
  172. bool AITurretShapeData::onAdd()
  173. {
  174. if (!Parent::onAdd())
  175. return false;
  176. // Copy state data from the scripting arrays into the
  177. // state structure array. If we have state data already,
  178. // we are on the client and need to leave it alone.
  179. for (U32 i = 0; i < MaxStates; i++) {
  180. StateData& s = state[i];
  181. if (statesLoaded == false) {
  182. s.name = stateName[i];
  183. s.transition.rest[0] = lookupState(stateTransitionNotAtRest[i]);
  184. s.transition.rest[1] = lookupState(stateTransitionAtRest[i]);
  185. s.transition.target[0] = lookupState(stateTransitionNoTarget[i]);
  186. s.transition.target[1] = lookupState(stateTransitionTarget[i]);
  187. s.transition.activated[0] = lookupState(stateTransitionDeactivated[i]);
  188. s.transition.activated[1] = lookupState(stateTransitionActivated[i]);
  189. s.transition.timeout = lookupState(stateTransitionTimeout[i]);
  190. s.waitForTimeout = stateWaitForTimeout[i];
  191. s.timeoutValue = stateTimeoutValue[i];
  192. s.fire = stateFire[i];
  193. s.scan = stateScan[i];
  194. s.scaleAnimation = stateScaleAnimation[i];
  195. s.direction = stateDirection[i];
  196. s.script = stateScript[i];
  197. // Resolved at load time
  198. s.sequence = -1;
  199. }
  200. // The first state marked as "fire" is the state entered on the
  201. // client when it recieves a fire event.
  202. if (s.fire && fireState == -1)
  203. fireState = i;
  204. }
  205. // Always preload images, this is needed to avoid problems with
  206. // resolving sequences before transmission to a client.
  207. return true;
  208. }
  209. bool AITurretShapeData::preload(bool server, String &errorStr)
  210. {
  211. if (!Parent::preload(server, errorStr))
  212. return false;
  213. // We have mShape at this point. Resolve nodes.
  214. scanNode = mShape->findNode("scanPoint");
  215. aimNode = mShape->findNode("aimPoint");
  216. if (aimNode == -1)
  217. {
  218. aimNode = pitchNode;
  219. }
  220. if (aimNode == -1)
  221. {
  222. aimNode = headingNode;
  223. }
  224. // Resolve state sequence names & emitter nodes
  225. isAnimated = false;
  226. for (U32 j = 0; j < MaxStates; j++) {
  227. StateData& s = state[j];
  228. if (stateSequence[j] && stateSequence[j][0])
  229. s.sequence = mShape->findSequence(stateSequence[j]);
  230. if (s.sequence != -1)
  231. {
  232. // This state has an animation sequence
  233. isAnimated = true;
  234. }
  235. }
  236. return true;
  237. }
  238. void AITurretShapeData::packData(BitStream* stream)
  239. {
  240. Parent::packData(stream);
  241. stream->write(maxScanHeading);
  242. stream->write(maxScanPitch);
  243. stream->write(maxScanDistance);
  244. stream->write(maxWeaponRange);
  245. stream->write(weaponLeadVelocity);
  246. for (U32 i = 0; i < MaxStates; i++)
  247. if (stream->writeFlag(state[i].name && state[i].name[0])) {
  248. StateData& s = state[i];
  249. // States info not needed on the client:
  250. // s.scriptNames
  251. // Transitions are inc. one to account for -1 values
  252. stream->writeString(state[i].name);
  253. stream->writeInt(s.transition.rest[0]+1,NumStateBits);
  254. stream->writeInt(s.transition.rest[1]+1,NumStateBits);
  255. stream->writeInt(s.transition.target[0]+1,NumStateBits);
  256. stream->writeInt(s.transition.target[1]+1,NumStateBits);
  257. stream->writeInt(s.transition.activated[0]+1,NumStateBits);
  258. stream->writeInt(s.transition.activated[1]+1,NumStateBits);
  259. stream->writeInt(s.transition.timeout+1,NumStateBits);
  260. if(stream->writeFlag(s.timeoutValue != gDefaultStateData.timeoutValue))
  261. stream->write(s.timeoutValue);
  262. stream->writeFlag(s.waitForTimeout);
  263. stream->writeFlag(s.fire);
  264. stream->writeFlag(s.scan);
  265. stream->writeFlag(s.scaleAnimation);
  266. stream->writeFlag(s.direction);
  267. if(stream->writeFlag(s.sequence != gDefaultStateData.sequence))
  268. stream->writeSignedInt(s.sequence, 16);
  269. }
  270. }
  271. void AITurretShapeData::unpackData(BitStream* stream)
  272. {
  273. Parent::unpackData(stream);
  274. stream->read(&maxScanHeading);
  275. stream->read(&maxScanPitch);
  276. stream->read(&maxScanDistance);
  277. stream->read(&maxWeaponRange);
  278. stream->read(&weaponLeadVelocity);
  279. for (U32 i = 0; i < MaxStates; i++) {
  280. if (stream->readFlag()) {
  281. StateData& s = state[i];
  282. // States info not needed on the client:
  283. // s.scriptNames
  284. // Transitions are dec. one to restore -1 values
  285. s.name = stream->readSTString();
  286. s.transition.rest[0] = stream->readInt(NumStateBits) - 1;
  287. s.transition.rest[1] = stream->readInt(NumStateBits) - 1;
  288. s.transition.target[0] = stream->readInt(NumStateBits) - 1;
  289. s.transition.target[1] = stream->readInt(NumStateBits) - 1;
  290. s.transition.activated[0] = stream->readInt(NumStateBits) - 1;
  291. s.transition.activated[1] = stream->readInt(NumStateBits) - 1;
  292. s.transition.timeout = stream->readInt(NumStateBits) - 1;
  293. if(stream->readFlag())
  294. stream->read(&s.timeoutValue);
  295. else
  296. s.timeoutValue = gDefaultStateData.timeoutValue;
  297. s.waitForTimeout = stream->readFlag();
  298. s.fire = stream->readFlag();
  299. s.scan = stream->readFlag();
  300. s.scaleAnimation = stream->readFlag();
  301. s.direction = stream->readFlag();
  302. if(stream->readFlag())
  303. s.sequence = stream->readSignedInt(16);
  304. }
  305. }
  306. statesLoaded = true;
  307. }
  308. S32 AITurretShapeData::lookupState(const char* name)
  309. {
  310. if (!name || !name[0])
  311. return -1;
  312. for (U32 i = 0; i < MaxStates; i++)
  313. if (stateName[i] && !dStricmp(name,stateName[i]))
  314. return i;
  315. Con::errorf(ConsoleLogEntry::General,"AITurretShapeData:: Could not resolve state \"%s\" for image \"%s\"",name,getName());
  316. return 0;
  317. }
  318. //----------------------------------------------------------------------------
  319. // Used to build potential target list
  320. static void _scanCallback( SceneObject* object, void* data )
  321. {
  322. AITurretShape* turret = (AITurretShape*)data;
  323. ShapeBase* shape = dynamic_cast<ShapeBase*>(object);
  324. if (shape && shape->getDamageState() == ShapeBase::Enabled)
  325. {
  326. Point3F targetPos = shape->getBoxCenter();
  327. // Put target position into the scan node's space
  328. turret->mScanWorkspaceScanWorldMat.mulP(targetPos);
  329. // Is the target within scanning distance
  330. if (targetPos.lenSquared() > turret->getMaxScanDistanceSquared())
  331. return;
  332. // Make sure the target is in front and within the maximum
  333. // heading range
  334. Point2F targetXY(targetPos.x, targetPos.y);
  335. targetXY.normalizeSafe();
  336. F32 headingDot = mDot(Point2F(0, 1), targetXY);
  337. F32 heading = mAcos(headingDot);
  338. if (headingDot < 0 || heading > turret->getMaxScanHeading())
  339. return;
  340. // Make sure the target is in front and within the maximum
  341. // pitch range
  342. Point2F targetZY(targetPos.z, targetPos.y);
  343. targetZY.normalizeSafe();
  344. F32 pitchDot = mDot(Point2F(0, 1), targetZY);
  345. F32 pitch = mAcos(pitchDot);
  346. if (pitchDot < 0 || pitch > turret->getMaxScanPitch())
  347. return;
  348. turret->addPotentialTarget(shape);
  349. }
  350. }
  351. // Used to sort potential target list based on distance
  352. static Point3F comparePoint;
  353. static S32 QSORT_CALLBACK _sortCallback(const void* a,const void* b)
  354. {
  355. const ShapeBase* s1 = (*reinterpret_cast<const ShapeBase* const*>(a));
  356. const ShapeBase* s2 = (*reinterpret_cast<const ShapeBase* const*>(b));
  357. F32 s1Len = (s1->getPosition() - comparePoint).lenSquared();
  358. F32 s2Len = (s2->getPosition() - comparePoint).lenSquared();
  359. return s1Len - s2Len;
  360. }
  361. IMPLEMENT_CO_NETOBJECT_V1(AITurretShape);
  362. ConsoleDocClass( AITurretShape,
  363. "@ingroup gameObjects"
  364. );
  365. AITurretShape::AITurretShape()
  366. {
  367. mTypeMask |= VehicleObjectType | DynamicShapeObjectType;
  368. mDataBlock = 0;
  369. mScanHeading = 0;
  370. mScanPitch = 0;
  371. mScanDistance = 0;
  372. mScanDistanceSquared = 0;
  373. mScanBox = Box3F::Zero;
  374. mScanTickFrequency = 1;
  375. mScanTickFrequencyVariance = 0;
  376. mTicksToNextScan = mScanTickFrequency;
  377. mWeaponRangeSquared = 0;
  378. mWeaponLeadVelocitySquared = 0;
  379. mScanForTargets = false;
  380. mTrackTarget = false;
  381. mState = NULL;
  382. mStateDelayTime = 0;
  383. mStateActive = true;
  384. mStateAnimThread = NULL;
  385. // For the TurretShape class
  386. mSubclassTurretShapeHandlesScene = true;
  387. }
  388. AITurretShape::~AITurretShape()
  389. {
  390. _cleanupPotentialTargets();
  391. }
  392. //----------------------------------------------------------------------------
  393. void AITurretShape::initPersistFields()
  394. {
  395. Parent::initPersistFields();
  396. }
  397. bool AITurretShape::onAdd()
  398. {
  399. if( !Parent::onAdd() )
  400. return false;
  401. // Add this object to the scene
  402. addToScene();
  403. _setScanBox();
  404. if (isServerObject())
  405. _initState();
  406. if (isServerObject())
  407. scriptOnAdd();
  408. return true;
  409. }
  410. void AITurretShape::onRemove()
  411. {
  412. Parent::onRemove();
  413. scriptOnRemove();
  414. mIgnoreObjects.clear();
  415. // Remove this object from the scene
  416. removeFromScene();
  417. }
  418. bool AITurretShape::onNewDataBlock(GameBaseData* dptr, bool reload)
  419. {
  420. mDataBlock = dynamic_cast<AITurretShapeData*>(dptr);
  421. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  422. return false;
  423. mScanHeading = mDegToRad(mDataBlock->maxScanHeading);
  424. if (mIsZero(mScanHeading))
  425. mScanHeading = M_PI_F;
  426. mScanPitch = mDegToRad(mDataBlock->maxScanPitch);
  427. if (mIsZero(mScanPitch))
  428. mScanPitch = M_PI_F;
  429. mScanDistance = mDataBlock->maxScanDistance;
  430. mScanDistanceSquared = mScanDistance * mScanDistance;
  431. mWeaponRangeSquared = mDataBlock->maxWeaponRange * mDataBlock->maxWeaponRange;
  432. mWeaponLeadVelocitySquared = (mDataBlock->weaponLeadVelocity > 0) ? (mDataBlock->weaponLeadVelocity * mDataBlock->weaponLeadVelocity) : 0;
  433. // The scan box is built such that the scanning origin is at (0,0,0) and the scanning distance
  434. // is out along the y axis. When this is transformed to the turret's location is provides a
  435. // scanning volume in front of the turret.
  436. F32 scanX = mScanDistance*mSin(mScanHeading);
  437. F32 scanY = mScanDistance;
  438. F32 scanZ = mScanDistance*mSin(mScanPitch);
  439. mScanBox.set(-scanX, 0, -scanZ, scanX, scanY, scanZ);
  440. mScanTickFrequency = mDataBlock->scanTickFrequency;
  441. if (mScanTickFrequency < 1)
  442. mScanTickFrequency = 1;
  443. mScanTickFrequencyVariance = mDataBlock->scanTickFrequencyVariance;
  444. if (mScanTickFrequencyVariance < 0)
  445. mScanTickFrequencyVariance = 0;
  446. mTicksToNextScan = mScanTickFrequency;
  447. // For states
  448. mStateAnimThread = 0;
  449. if (mDataBlock->isAnimated)
  450. {
  451. mStateAnimThread = mShapeInstance->addThread();
  452. mShapeInstance->setTimeScale(mStateAnimThread,0);
  453. }
  454. scriptOnNewDataBlock();
  455. return true;
  456. }
  457. //----------------------------------------------------------------------------
  458. void AITurretShape::addToIgnoreList(ShapeBase* obj)
  459. {
  460. mIgnoreObjects.addObject(obj);
  461. }
  462. void AITurretShape::removeFromIgnoreList(ShapeBase* obj)
  463. {
  464. mIgnoreObjects.removeObject(obj);
  465. }
  466. //----------------------------------------------------------------------------
  467. void AITurretShape::_initState()
  468. {
  469. // Set the turret to its starting state.
  470. setTurretState(0, true);
  471. }
  472. void AITurretShape::setTurretStateName(const char* newState, bool force)
  473. {
  474. S32 stateVal = mDataBlock->lookupState(newState);
  475. if (stateVal >= 0)
  476. {
  477. setTurretState(stateVal, force);
  478. }
  479. }
  480. void AITurretShape::setTurretState(U32 newState, bool force)
  481. {
  482. setMaskBits(TurretStateMask);
  483. // If going back into the same state, just reset the timer
  484. // and invoke the script callback
  485. if (!force && mState == &mDataBlock->state[newState])
  486. {
  487. mStateDelayTime = mState->timeoutValue;
  488. if (mState->script && !isGhost())
  489. _scriptCallback(mState->script);
  490. return;
  491. }
  492. mState = &mDataBlock->state[newState];
  493. // Reset cyclic sequences back to the first frame to turn it off
  494. // (the first key frame should be it's off state).
  495. if (mStateAnimThread && mStateAnimThread->getSequence()->isCyclic())
  496. {
  497. mShapeInstance->setPos(mStateAnimThread,0);
  498. mShapeInstance->setTimeScale(mStateAnimThread,0);
  499. }
  500. AITurretShapeData::StateData& stateData = *mState;
  501. // Check for immediate transitions
  502. S32 ns;
  503. if ((ns = stateData.transition.rest[mAtRest]) != -1)
  504. {
  505. setTurretState(ns);
  506. return;
  507. }
  508. if ((ns = stateData.transition.target[mTarget.isValid()]) != -1)
  509. {
  510. setTurretState(ns);
  511. return;
  512. }
  513. if ((ns = stateData.transition.activated[mStateActive]) != -1)
  514. {
  515. setTurretState(ns);
  516. return;
  517. }
  518. //
  519. // Initialize the new state...
  520. //
  521. mStateDelayTime = stateData.timeoutValue;
  522. // Play animation
  523. if (mStateAnimThread && stateData.sequence != -1)
  524. {
  525. mShapeInstance->setSequence(mStateAnimThread,stateData.sequence, stateData.direction ? 0.0f : 1.0f);
  526. F32 timeScale = (stateData.scaleAnimation && stateData.timeoutValue) ?
  527. mShapeInstance->getDuration(mStateAnimThread) / stateData.timeoutValue : 1.0f;
  528. mShapeInstance->setTimeScale(mStateAnimThread, stateData.direction ? timeScale : -timeScale);
  529. }
  530. // Script callback on server
  531. if (stateData.script && stateData.script[0] && !isGhost())
  532. _scriptCallback(stateData.script);
  533. // If there is a zero timeout, and a timeout transition, then
  534. // go ahead and transition imediately.
  535. if (!mStateDelayTime)
  536. {
  537. if ((ns = stateData.transition.timeout) != -1)
  538. {
  539. setTurretState(ns);
  540. return;
  541. }
  542. }
  543. }
  544. void AITurretShape::_updateTurretState(F32 dt)
  545. {
  546. AITurretShapeData::StateData& stateData = *mState;
  547. mStateDelayTime -= dt;
  548. // Check for transitions. On some states we must wait for the
  549. // full timeout value before moving on.
  550. if (mStateDelayTime <= 0 || !stateData.waitForTimeout)
  551. {
  552. S32 ns;
  553. if ((ns = stateData.transition.rest[mAtRest]) != -1)
  554. setTurretState(ns);
  555. else if ((ns = stateData.transition.target[mTarget.isValid()]) != -1)
  556. setTurretState(ns);
  557. else if ((ns = stateData.transition.activated[mStateActive]) != -1)
  558. setTurretState(ns);
  559. else if (mStateDelayTime <= 0 && (ns = stateData.transition.timeout) != -1)
  560. setTurretState(ns);
  561. }
  562. }
  563. void AITurretShape::_scriptCallback(const char* function)
  564. {
  565. Con::executef( mDataBlock, function, getIdString() );
  566. }
  567. //----------------------------------------------------------------------------
  568. void AITurretShape::_cleanupPotentialTargets()
  569. {
  570. mPotentialTargets.clear();
  571. }
  572. void AITurretShape::_performScan()
  573. {
  574. // Only on server
  575. if (isClientObject())
  576. return;
  577. // Are we ready for a scan?
  578. --mTicksToNextScan;
  579. if (mTicksToNextScan > 0)
  580. return;
  581. _cleanupPotentialTargets();
  582. _setScanBox();
  583. // Set up for the scan
  584. getScanTransform(mScanWorkspaceScanMat);
  585. mScanWorkspaceScanWorldMat = mScanWorkspaceScanMat;
  586. mScanWorkspaceScanWorldMat.affineInverse();
  587. disableCollision();
  588. for ( SimSetIterator iter(&mIgnoreObjects); *iter; ++iter )
  589. {
  590. ShapeBase* obj = static_cast<ShapeBase*>( *iter );
  591. obj->disableCollision();
  592. }
  593. gServerContainer.findObjects( mTransformedScanBox, sScanTypeMask, _scanCallback, (void*)this );
  594. for ( SimSetIterator iter(&mIgnoreObjects); *iter; ++iter )
  595. {
  596. ShapeBase* obj = static_cast<ShapeBase*>( *iter );
  597. obj->enableCollision();
  598. }
  599. enableCollision();
  600. if (mPotentialTargets.size() == 0)
  601. {
  602. // No targets in range. Clear out our current target, if necessary.
  603. _lostTarget();
  604. }
  605. else
  606. {
  607. // Sort the targets
  608. comparePoint = getPosition();
  609. dQsort(mPotentialTargets.address(),mPotentialTargets.size(),sizeof(SimObjectList::value_type),_sortCallback);
  610. // Go through the targets in order to find one that is not blocked from view
  611. Point3F start;
  612. mScanWorkspaceScanMat.getColumn(3, &start);
  613. S32 index = 0;
  614. bool los = false;
  615. disableCollision();
  616. for (index=0; index < mPotentialTargets.size(); ++index)
  617. {
  618. ShapeBase* shape = (ShapeBase*)mPotentialTargets[index];
  619. Point3F sightPoint;
  620. los = _testTargetLineOfSight(start, shape, sightPoint);
  621. // Check if we have a clear line of sight
  622. if (los)
  623. break;
  624. }
  625. enableCollision();
  626. // If we found a valid, visible target (no hits between here and there), latch on to it
  627. if (los)
  628. {
  629. _gainedTarget((ShapeBase*)mPotentialTargets[index]);
  630. }
  631. }
  632. // Prepare for next scan period
  633. mTicksToNextScan = mScanTickFrequency;
  634. if (mScanTickFrequencyVariance > 0)
  635. {
  636. mTicksToNextScan += gRandGen.randI(0, mScanTickFrequencyVariance);
  637. }
  638. }
  639. void AITurretShape::addPotentialTarget(ShapeBase* shape)
  640. {
  641. mPotentialTargets.push_back(shape);
  642. }
  643. void AITurretShape::_lostTarget()
  644. {
  645. mTarget.target = NULL;
  646. }
  647. void AITurretShape::_gainedTarget(ShapeBase* target)
  648. {
  649. mTarget.target = target;
  650. if (target)
  651. {
  652. mTarget.hadValidTarget = true;
  653. }
  654. }
  655. void AITurretShape::_trackTarget(F32 dt)
  656. {
  657. // Only on server
  658. if (isClientObject())
  659. return;
  660. // We can only track a target if we have one
  661. if (!mTarget.isValid())
  662. return;
  663. Point3F targetPos = mTarget.target->getBoxCenter();
  664. // Can we see the target?
  665. MatrixF aimMat;
  666. getAimTransform(aimMat);
  667. Point3F start;
  668. aimMat.getColumn(3, &start);
  669. RayInfo ri;
  670. Point3F sightPoint;
  671. disableCollision();
  672. bool los = _testTargetLineOfSight(start, mTarget.target, sightPoint);
  673. enableCollision();
  674. if (!los)
  675. {
  676. // Target is blocked. Should we try to track from its last
  677. // known position and velocity?
  678. SimTime curTime = Sim::getCurrentTime();
  679. if ( (curTime - mTarget.lastSightTime) > (mDataBlock->trackLostTargetTime * 1000.0f) )
  680. {
  681. // Time's up. Stop tracking.
  682. _cleanupTargetAndTurret();
  683. return;
  684. }
  685. // Use last known information to attempt to
  686. // continue to track target for a while.
  687. targetPos = mTarget.lastPos + mTarget.lastVel * F32(curTime - mTarget.lastSightTime) / 1000.0f;
  688. }
  689. else
  690. {
  691. // Target is visible
  692. // We only track targets that are alive
  693. if (mTarget.target->getDamageState() != Enabled)
  694. {
  695. // We can't track any more
  696. _cleanupTargetAndTurret();
  697. return;
  698. }
  699. targetPos = sightPoint;
  700. // Store latest target info
  701. mTarget.lastPos = targetPos;
  702. mTarget.lastVel = mTarget.target->getVelocity();
  703. mTarget.lastSightTime = Sim::getCurrentTime();
  704. }
  705. // Calculate angles to face the target, specifically the part that we can see
  706. VectorF toTarget;
  707. MatrixF mat;
  708. S32 node = mDataBlock->aimNode;
  709. if (node != -1)
  710. {
  711. // Get the current position of our node
  712. MatrixF* nodeTrans = &mShapeInstance->mNodeTransforms[node];
  713. Point3F currentPos;
  714. nodeTrans->getColumn(3, &currentPos);
  715. // Turn this into a matrix we can use to put the target
  716. // position into our space.
  717. MatrixF nodeMat(true);
  718. nodeMat.setColumn(3, currentPos);
  719. mat.mul(mObjToWorld, nodeMat);
  720. mat.affineInverse();
  721. }
  722. else
  723. {
  724. mat = mWorldToObj;
  725. }
  726. mat.mulP(targetPos, &toTarget);
  727. // lead the target
  728. F32 timeToTargetSquared = (mWeaponLeadVelocitySquared > 0) ? toTarget.lenSquared() / mWeaponLeadVelocitySquared : 0;
  729. if (timeToTargetSquared > 1.0)
  730. {
  731. targetPos = targetPos + (mTarget.lastVel * mSqrt(timeToTargetSquared));
  732. mat.mulP(targetPos, &toTarget);
  733. }
  734. F32 yaw, pitch;
  735. MathUtils::getAnglesFromVector(toTarget, yaw, pitch);
  736. if (yaw > M_PI_F)
  737. yaw = yaw - M_2PI_F;
  738. //if (pitch > M_PI_F)
  739. // pitch = -(pitch - M_2PI_F);
  740. Point3F rot(-pitch, 0.0f, yaw);
  741. // If we have a rotation rate make sure we follow it
  742. if (mHeadingRate > 0)
  743. {
  744. F32 rate = mHeadingRate * dt;
  745. F32 rateCheck = mFabs(rot.z - mRot.z);
  746. if (rateCheck > rate)
  747. {
  748. // This will clamp the new value to the rate regardless if it
  749. // is increasing or decreasing.
  750. rot.z = mClampF(rot.z, mRot.z-rate, mRot.z+rate);
  751. }
  752. }
  753. if (mPitchRate > 0)
  754. {
  755. F32 rate = mPitchRate * dt;
  756. F32 rateCheck = mFabs(rot.x - mRot.x);
  757. if (rateCheck > rate)
  758. {
  759. // This will clamp the new value to the rate regardless if it
  760. // is increasing or decreasing.
  761. rot.x = mClampF(rot.x, mRot.x-rate, mRot.x+rate);
  762. }
  763. }
  764. // Test if the rotation to the target is outside of our limits
  765. if (_outsideLimits(rot))
  766. {
  767. // We can't track any more
  768. _cleanupTargetAndTurret();
  769. return;
  770. }
  771. // Test if the target is out of weapons range
  772. if (toTarget.lenSquared() > mWeaponRangeSquared)
  773. {
  774. // We can't track any more
  775. _cleanupTargetAndTurret();
  776. return;
  777. }
  778. mRot = rot;
  779. _setRotation( mRot );
  780. setMaskBits(TurretUpdateMask);
  781. }
  782. void AITurretShape::_cleanupTargetAndTurret()
  783. {
  784. _lostTarget();
  785. resetTarget();
  786. }
  787. bool AITurretShape::_testTargetLineOfSight(Point3F& aimPoint, ShapeBase* target, Point3F& sightPoint)
  788. {
  789. Point3F targetCenter = target->getBoxCenter();
  790. RayInfo ri;
  791. bool hit = false;
  792. target->disableCollision();
  793. // First check for a clear line of sight to the target's center
  794. Point3F testPoint = targetCenter;
  795. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  796. if (hit)
  797. {
  798. // No clear line of sight to center, so try to the target's right. Players holding
  799. // a gun in their right hand will tend to stick their right shoulder out first if
  800. // they're peering around some cover to shoot, like a wall.
  801. Box3F targetBounds = target->getObjBox();
  802. F32 radius = targetBounds.len_x() > targetBounds.len_y() ? targetBounds.len_x() : targetBounds.len_y();
  803. radius *= 0.5;
  804. VectorF toTurret = aimPoint - targetCenter;
  805. toTurret.normalizeSafe();
  806. VectorF toTurretRight = mCross(toTurret, Point3F::UnitZ);
  807. testPoint = targetCenter + toTurretRight * radius;
  808. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  809. if (hit)
  810. {
  811. // No clear line of sight to right, so try the target's left
  812. VectorF toTurretLeft = toTurretRight * -1.0f;
  813. testPoint = targetCenter + toTurretLeft * radius;
  814. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  815. }
  816. if (hit)
  817. {
  818. // No clear line of sight to left, so try the target's top
  819. testPoint = targetCenter;
  820. testPoint.z += targetBounds.len_z() * 0.5f;
  821. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  822. }
  823. if (hit)
  824. {
  825. // No clear line of sight to top, so try the target's bottom
  826. testPoint = targetCenter;
  827. testPoint.z -= targetBounds.len_z() * 0.5f;
  828. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  829. }
  830. }
  831. target->enableCollision();
  832. if (!hit)
  833. {
  834. // Line of sight point is that last one we tested
  835. sightPoint = testPoint;
  836. }
  837. return !hit;
  838. }
  839. //----------------------------------------------------------------------------
  840. void AITurretShape::setAllGunsFiring(bool fire)
  841. {
  842. setImageTriggerState(0,fire);
  843. setImageTriggerState(1,fire);
  844. setImageTriggerState(2,fire);
  845. setImageTriggerState(3,fire);
  846. }
  847. void AITurretShape::setGunSlotFiring(S32 slot, bool fire)
  848. {
  849. if (slot < 0 || slot > 3)
  850. return;
  851. setImageTriggerState(slot, fire);
  852. }
  853. //----------------------------------------------------------------------------
  854. void AITurretShape::setTransform(const MatrixF& mat)
  855. {
  856. Parent::setTransform(mat);
  857. // Set the scanning box
  858. _setScanBox();
  859. }
  860. void AITurretShape::recenterTurret()
  861. {
  862. mRot.set(0,0,0);
  863. _setRotation( mRot );
  864. setMaskBits(TurretUpdateMask);
  865. }
  866. void AITurretShape::_setScanBox()
  867. {
  868. mTransformedScanBox = mScanBox;
  869. MatrixF mat;
  870. getScanTransform(mat);
  871. mat.mul(mTransformedScanBox);
  872. }
  873. void AITurretShape::getScanTransform(MatrixF& mat)
  874. {
  875. if (mDataBlock && mDataBlock->scanNode != -1)
  876. {
  877. if (getNodeTransform(mDataBlock->scanNode, mat))
  878. {
  879. return;
  880. }
  881. }
  882. mat = mObjToWorld;
  883. }
  884. void AITurretShape::getAimTransform(MatrixF& mat)
  885. {
  886. if (mDataBlock && mDataBlock->aimNode != -1)
  887. {
  888. if (getNodeTransform(mDataBlock->aimNode, mat))
  889. {
  890. return;
  891. }
  892. }
  893. mat = mObjToWorld;
  894. }
  895. //----------------------------------------------------------------------------
  896. void AITurretShape::processTick(const Move* move)
  897. {
  898. Parent::processTick(move);
  899. if (isServerObject() && mDamageState == Enabled)
  900. {
  901. _updateTurretState(TickSec);
  902. if (mScanForTargets)
  903. {
  904. // Perform a scan for targets
  905. _performScan();
  906. // If we found one, turn off the scan
  907. if (mTarget.isValid())
  908. {
  909. mScanForTargets = false;
  910. }
  911. }
  912. if (mTrackTarget)
  913. {
  914. _trackTarget(TickSec);
  915. // If the target is lost, no longer track it
  916. if (!mTarget.isValid())
  917. {
  918. mTrackTarget = false;
  919. }
  920. }
  921. }
  922. }
  923. void AITurretShape::advanceTime(F32 dt)
  924. {
  925. // If there were any ShapeBase script threads that
  926. // have played, then we need to update all code
  927. // controlled nodes. This is done before the Parent
  928. // call as script threads may play and be destroyed
  929. // before our code is called.
  930. bool updateNodes = false;
  931. for (U32 i = 0; i < MaxScriptThreads; i++)
  932. {
  933. Thread& st = mScriptThread[i];
  934. if (st.thread)
  935. {
  936. updateNodes = true;
  937. break;
  938. }
  939. }
  940. Parent::advanceTime(dt);
  941. // Update any state thread
  942. AITurretShapeData::StateData& stateData = *mState;
  943. if (mStateAnimThread && stateData.sequence != -1)
  944. {
  945. mShapeInstance->advanceTime(dt,mStateAnimThread);
  946. updateNodes = true;
  947. }
  948. if (updateNodes)
  949. {
  950. // Update all code controlled nodes
  951. _updateNodes(mRot);
  952. }
  953. }
  954. //----------------------------------------------------------------------------
  955. U32 AITurretShape::packUpdate(NetConnection *connection, U32 mask, BitStream *bstream)
  956. {
  957. U32 retMask = Parent::packUpdate(connection,mask,bstream);
  958. // Indicate that the transform has changed to update the scan box
  959. bstream->writeFlag(mask & (PositionMask | ExtendedInfoMask));
  960. // Handle any state changes that need to be passed along
  961. if (bstream->writeFlag(mask & TurretStateMask))
  962. {
  963. bstream->write(mDataBlock->lookupState(mState->name));
  964. }
  965. return retMask;
  966. }
  967. void AITurretShape::unpackUpdate(NetConnection *connection, BitStream *bstream)
  968. {
  969. Parent::unpackUpdate(connection,bstream);
  970. // Transform has changed
  971. if (bstream->readFlag())
  972. {
  973. _setScanBox();
  974. }
  975. //TurretStateMask
  976. if (bstream->readFlag())
  977. {
  978. S32 newstate;
  979. bstream->read( &newstate );
  980. setTurretState(newstate);
  981. }
  982. }
  983. //----------------------------------------------------------------------------
  984. void AITurretShape::prepBatchRender( SceneRenderState *state, S32 mountedImageIndex )
  985. {
  986. Parent::prepBatchRender( state, mountedImageIndex );
  987. if ( !gShowBoundingBox )
  988. return;
  989. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  990. ri->renderDelegate.bind( this, &AITurretShape::_renderScanner );
  991. ri->type = RenderPassManager::RIT_Editor;
  992. state->getRenderPass()->addInst( ri );
  993. }
  994. void AITurretShape::_renderScanner( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  995. {
  996. GFXStateBlockDesc desc;
  997. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  998. desc.setZReadWrite(false,true);
  999. desc.fillMode = GFXFillWireframe;
  1000. // Render the scan box
  1001. GFX->getDrawUtil()->drawCube(desc, mTransformedScanBox.getExtents(), mTransformedScanBox.getCenter(), ColorI(255, 0, 0));
  1002. // Render a line from the scan node to the max scan distance
  1003. MatrixF nodeMat;
  1004. if (getNodeTransform(mDataBlock->scanNode, nodeMat))
  1005. {
  1006. Point3F start;
  1007. nodeMat.getColumn(3, &start);
  1008. Point3F end(0.0f, mScanDistance, 0.0f);
  1009. nodeMat.mulP(end);
  1010. GFX->getDrawUtil()->drawLine(start, end, ColorI(255, 255, 0));
  1011. }
  1012. }
  1013. //----------------------------------------------------------------------------
  1014. DefineEngineMethod( AITurretShape, addToIgnoreList, void, (ShapeBase* obj),,
  1015. "@brief Adds object to the turret's ignore list.\n\n"
  1016. "All objects in this list will be ignored by the turret's targeting.\n"
  1017. "@param obj The ShapeBase object to ignore.\n")
  1018. {
  1019. object->addToIgnoreList(obj);
  1020. }
  1021. DefineEngineMethod( AITurretShape, removeFromIgnoreList, void, (ShapeBase* obj),,
  1022. "@brief Removes object from the turret's ignore list.\n\n"
  1023. "All objects in this list will be ignored by the turret's targeting.\n"
  1024. "@param obj The ShapeBase object to once again allow for targeting.\n")
  1025. {
  1026. object->removeFromIgnoreList(obj);
  1027. }
  1028. DefineEngineMethod( AITurretShape, setTurretState, void, (const char* newState, bool force), (false),
  1029. "@brief Set the turret's current state.\n\n"
  1030. "Normally the turret's state comes from updating the state machine but this method "
  1031. "allows you to override this and jump to the requested state immediately.\n"
  1032. "@param newState The name of the new state.\n"
  1033. "@param force Is true then force the full processing of the new state even if it is the "
  1034. "same as the current state. If false then only the time out value is reset and the state's "
  1035. "script method is called, if any.\n")
  1036. {
  1037. object->setTurretStateName(newState, force);
  1038. }
  1039. DefineEngineMethod( AITurretShape, activateTurret, void, ( ),,
  1040. "@brief Activate a turret from a deactive state.\n\n")
  1041. {
  1042. object->activateTurret();
  1043. }
  1044. DefineEngineMethod( AITurretShape, deactivateTurret, void, ( ),,
  1045. "@brief Deactivate a turret from an active state.\n\n")
  1046. {
  1047. object->deactivateTurret();
  1048. }
  1049. DefineEngineMethod( AITurretShape, startScanForTargets, void, ( ),,
  1050. "@brief Begin scanning for a target.\n\n")
  1051. {
  1052. object->startScanForTargets();
  1053. }
  1054. DefineEngineMethod( AITurretShape, stopScanForTargets, void, ( ),,
  1055. "@brief Stop scanning for targets.\n\n"
  1056. "@note Only impacts the scanning for new targets. Does not effect a turret's current "
  1057. "target lock.\n")
  1058. {
  1059. object->stopScanForTargets();
  1060. }
  1061. DefineEngineMethod( AITurretShape, startTrackingTarget, void, ( ),,
  1062. "@brief Have the turret track the current target.\n\n")
  1063. {
  1064. object->startTrackingTarget();
  1065. }
  1066. DefineEngineMethod( AITurretShape, stopTrackingTarget, void, ( ),,
  1067. "@brief Stop the turret from tracking the current target.\n\n")
  1068. {
  1069. object->stopTrackingTarget();
  1070. }
  1071. DefineEngineMethod( AITurretShape, hasTarget, bool, (),,
  1072. "@brief Indicates if the turret has a target.\n\n"
  1073. "@returns True if the turret has a target.\n")
  1074. {
  1075. return object->hasTarget();
  1076. }
  1077. DefineEngineMethod( AITurretShape, getTarget, SimObject*, (),,
  1078. "@brief Get the turret's current target.\n\n"
  1079. "@returns The object that is the target's current target, or 0 if no target.\n")
  1080. {
  1081. return object->getTarget();
  1082. }
  1083. DefineEngineMethod( AITurretShape, resetTarget, void, ( ),,
  1084. "@brief Resets the turret's target tracking.\n\n"
  1085. "Only resets the internal target tracking. Does not modify the turret's facing.\n")
  1086. {
  1087. object->resetTarget();
  1088. }
  1089. DefineEngineMethod( AITurretShape, setWeaponLeadVelocity, void, (F32 velocity),,
  1090. "@brief Set the turret's projectile velocity to help lead the target.\n\n"
  1091. "This value normally comes from AITurretShapeData::weaponLeadVelocity but this method "
  1092. "allows you to override the datablock value. This can be useful if the turret changes "
  1093. "ammunition, uses a different weapon than the default, is damaged, etc.\n"
  1094. "@note Setting this to 0 will disable target leading.\n")
  1095. {
  1096. object->setWeaponLeadVelocity(velocity);
  1097. }
  1098. DefineEngineMethod( AITurretShape, getWeaponLeadVelocity, F32, (),,
  1099. "@brief Get the turret's defined projectile velocity that helps with target leading.\n\n"
  1100. "@returns The defined weapon projectile speed, or 0 if leading is disabled.\n")
  1101. {
  1102. return object->getWeaponLeadVelocity();
  1103. }
  1104. DefineEngineMethod( AITurretShape, setAllGunsFiring, void, (bool fire),,
  1105. "@brief Set the firing state of the turret's guns.\n\n"
  1106. "@param fire Set to true to activate all guns. False to deactivate them.\n")
  1107. {
  1108. object->setAllGunsFiring(fire);
  1109. }
  1110. DefineEngineMethod( AITurretShape, setGunSlotFiring, void, (S32 slot, bool fire),,
  1111. "@brief Set the firing state of the given gun slot.\n\n"
  1112. "@param slot The gun to modify. Valid range is 0-3 that corresponds to the weapon mount point.\n"
  1113. "@param fire Set to true to activate the gun. False to deactivate it.\n")
  1114. {
  1115. object->setGunSlotFiring(slot, fire);
  1116. }
  1117. DefineEngineMethod( AITurretShape, recenterTurret, void, ( ),,
  1118. "@brief Recenter the turret's weapon.\n\n")
  1119. {
  1120. object->recenterTurret();
  1121. }