aiTurretShape.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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. void AITurretShape::clearIgnoreList()
  467. {
  468. mIgnoreObjects.clear();
  469. }
  470. S32 AITurretShape::ignoreListCount()
  471. {
  472. return mIgnoreObjects.size();
  473. }
  474. SimObject* AITurretShape::getIgnoreListObject(S32 index)
  475. {
  476. return mIgnoreObjects.at(index);
  477. }
  478. //----------------------------------------------------------------------------
  479. void AITurretShape::_initState()
  480. {
  481. // Set the turret to its starting state.
  482. setTurretState(0, true);
  483. }
  484. void AITurretShape::setTurretStateName(const char* newState, bool force)
  485. {
  486. S32 stateVal = mDataBlock->lookupState(newState);
  487. if (stateVal >= 0)
  488. {
  489. setTurretState(stateVal, force);
  490. }
  491. }
  492. void AITurretShape::setTurretState(U32 newState, bool force)
  493. {
  494. setMaskBits(TurretStateMask);
  495. // If going back into the same state, just reset the timer
  496. // and invoke the script callback
  497. if (!force && mState == &mDataBlock->state[newState])
  498. {
  499. mStateDelayTime = mState->timeoutValue;
  500. if (mState->script && !isGhost())
  501. _scriptCallback(mState->script);
  502. return;
  503. }
  504. mState = &mDataBlock->state[newState];
  505. // Reset cyclic sequences back to the first frame to turn it off
  506. // (the first key frame should be it's off state).
  507. if (mStateAnimThread && mStateAnimThread->getSequence()->isCyclic())
  508. {
  509. mShapeInstance->setPos(mStateAnimThread,0);
  510. mShapeInstance->setTimeScale(mStateAnimThread,0);
  511. }
  512. AITurretShapeData::StateData& stateData = *mState;
  513. // Check for immediate transitions
  514. S32 ns;
  515. if ((ns = stateData.transition.rest[mAtRest]) != -1)
  516. {
  517. setTurretState(ns);
  518. return;
  519. }
  520. if ((ns = stateData.transition.target[mTarget.isValid()]) != -1)
  521. {
  522. setTurretState(ns);
  523. return;
  524. }
  525. if ((ns = stateData.transition.activated[mStateActive]) != -1)
  526. {
  527. setTurretState(ns);
  528. return;
  529. }
  530. //
  531. // Initialize the new state...
  532. //
  533. mStateDelayTime = stateData.timeoutValue;
  534. // Play animation
  535. if (mStateAnimThread && stateData.sequence != -1)
  536. {
  537. mShapeInstance->setSequence(mStateAnimThread,stateData.sequence, stateData.direction ? 0.0f : 1.0f);
  538. F32 timeScale = (stateData.scaleAnimation && stateData.timeoutValue) ?
  539. mShapeInstance->getDuration(mStateAnimThread) / stateData.timeoutValue : 1.0f;
  540. mShapeInstance->setTimeScale(mStateAnimThread, stateData.direction ? timeScale : -timeScale);
  541. }
  542. // Script callback on server
  543. if (stateData.script && stateData.script[0] && !isGhost())
  544. _scriptCallback(stateData.script);
  545. // If there is a zero timeout, and a timeout transition, then
  546. // go ahead and transition imediately.
  547. if (!mStateDelayTime)
  548. {
  549. if ((ns = stateData.transition.timeout) != -1)
  550. {
  551. setTurretState(ns);
  552. return;
  553. }
  554. }
  555. }
  556. void AITurretShape::_updateTurretState(F32 dt)
  557. {
  558. AITurretShapeData::StateData& stateData = *mState;
  559. mStateDelayTime -= dt;
  560. // Check for transitions. On some states we must wait for the
  561. // full timeout value before moving on.
  562. if (mStateDelayTime <= 0 || !stateData.waitForTimeout)
  563. {
  564. S32 ns;
  565. if ((ns = stateData.transition.rest[mAtRest]) != -1)
  566. setTurretState(ns);
  567. else if ((ns = stateData.transition.target[mTarget.isValid()]) != -1)
  568. setTurretState(ns);
  569. else if ((ns = stateData.transition.activated[mStateActive]) != -1)
  570. setTurretState(ns);
  571. else if (mStateDelayTime <= 0 && (ns = stateData.transition.timeout) != -1)
  572. setTurretState(ns);
  573. }
  574. }
  575. void AITurretShape::_scriptCallback(const char* function)
  576. {
  577. Con::executef( mDataBlock, function, getIdString() );
  578. }
  579. //----------------------------------------------------------------------------
  580. void AITurretShape::_cleanupPotentialTargets()
  581. {
  582. mPotentialTargets.clear();
  583. }
  584. void AITurretShape::_performScan()
  585. {
  586. // Only on server
  587. if (isClientObject())
  588. return;
  589. // Are we ready for a scan?
  590. --mTicksToNextScan;
  591. if (mTicksToNextScan > 0)
  592. return;
  593. _cleanupPotentialTargets();
  594. _setScanBox();
  595. // Set up for the scan
  596. getScanTransform(mScanWorkspaceScanMat);
  597. mScanWorkspaceScanWorldMat = mScanWorkspaceScanMat;
  598. mScanWorkspaceScanWorldMat.affineInverse();
  599. disableCollision();
  600. for ( SimSetIterator iter(&mIgnoreObjects); *iter; ++iter )
  601. {
  602. ShapeBase* obj = static_cast<ShapeBase*>( *iter );
  603. obj->disableCollision();
  604. }
  605. gServerContainer.findObjects( mTransformedScanBox, sScanTypeMask, _scanCallback, (void*)this );
  606. for ( SimSetIterator iter(&mIgnoreObjects); *iter; ++iter )
  607. {
  608. ShapeBase* obj = static_cast<ShapeBase*>( *iter );
  609. obj->enableCollision();
  610. }
  611. enableCollision();
  612. if (mPotentialTargets.size() == 0)
  613. {
  614. // No targets in range. Clear out our current target, if necessary.
  615. _lostTarget();
  616. }
  617. else
  618. {
  619. // Sort the targets
  620. comparePoint = getPosition();
  621. dQsort(mPotentialTargets.address(),mPotentialTargets.size(),sizeof(SimObjectList::value_type),_sortCallback);
  622. // Go through the targets in order to find one that is not blocked from view
  623. Point3F start;
  624. mScanWorkspaceScanMat.getColumn(3, &start);
  625. S32 index = 0;
  626. bool los = false;
  627. disableCollision();
  628. for (index=0; index < mPotentialTargets.size(); ++index)
  629. {
  630. ShapeBase* shape = (ShapeBase*)mPotentialTargets[index];
  631. Point3F sightPoint;
  632. los = _testTargetLineOfSight(start, shape, sightPoint);
  633. // Check if we have a clear line of sight
  634. if (los)
  635. break;
  636. }
  637. enableCollision();
  638. // If we found a valid, visible target (no hits between here and there), latch on to it
  639. if (los)
  640. {
  641. _gainedTarget((ShapeBase*)mPotentialTargets[index]);
  642. }
  643. }
  644. // Prepare for next scan period
  645. mTicksToNextScan = mScanTickFrequency;
  646. if (mScanTickFrequencyVariance > 0)
  647. {
  648. mTicksToNextScan += gRandGen.randI(0, mScanTickFrequencyVariance);
  649. }
  650. }
  651. void AITurretShape::addPotentialTarget(ShapeBase* shape)
  652. {
  653. mPotentialTargets.push_back(shape);
  654. }
  655. void AITurretShape::_lostTarget()
  656. {
  657. mTarget.target = NULL;
  658. }
  659. void AITurretShape::_gainedTarget(ShapeBase* target)
  660. {
  661. mTarget.target = target;
  662. if (target)
  663. {
  664. mTarget.hadValidTarget = true;
  665. }
  666. }
  667. void AITurretShape::_trackTarget(F32 dt)
  668. {
  669. // Only on server
  670. if (isClientObject())
  671. return;
  672. // We can only track a target if we have one
  673. if (!mTarget.isValid())
  674. return;
  675. Point3F targetPos = mTarget.target->getBoxCenter();
  676. // Can we see the target?
  677. MatrixF aimMat;
  678. getAimTransform(aimMat);
  679. Point3F start;
  680. aimMat.getColumn(3, &start);
  681. RayInfo ri;
  682. Point3F sightPoint;
  683. disableCollision();
  684. bool los = _testTargetLineOfSight(start, mTarget.target, sightPoint);
  685. enableCollision();
  686. if (!los)
  687. {
  688. // Target is blocked. Should we try to track from its last
  689. // known position and velocity?
  690. SimTime curTime = Sim::getCurrentTime();
  691. if ( (curTime - mTarget.lastSightTime) > (mDataBlock->trackLostTargetTime * 1000.0f) )
  692. {
  693. // Time's up. Stop tracking.
  694. _cleanupTargetAndTurret();
  695. return;
  696. }
  697. // Use last known information to attempt to
  698. // continue to track target for a while.
  699. targetPos = mTarget.lastPos + mTarget.lastVel * F32(curTime - mTarget.lastSightTime) / 1000.0f;
  700. }
  701. else
  702. {
  703. // Target is visible
  704. // We only track targets that are alive
  705. if (mTarget.target->getDamageState() != Enabled)
  706. {
  707. // We can't track any more
  708. _cleanupTargetAndTurret();
  709. return;
  710. }
  711. targetPos = sightPoint;
  712. // Store latest target info
  713. mTarget.lastPos = targetPos;
  714. mTarget.lastVel = mTarget.target->getVelocity();
  715. mTarget.lastSightTime = Sim::getCurrentTime();
  716. }
  717. // Calculate angles to face the target, specifically the part that we can see
  718. VectorF toTarget;
  719. MatrixF mat;
  720. S32 node = mDataBlock->aimNode;
  721. if (node != -1)
  722. {
  723. // Get the current position of our node
  724. MatrixF* nodeTrans = &mShapeInstance->mNodeTransforms[node];
  725. Point3F currentPos;
  726. nodeTrans->getColumn(3, &currentPos);
  727. // Turn this into a matrix we can use to put the target
  728. // position into our space.
  729. MatrixF nodeMat(true);
  730. nodeMat.setColumn(3, currentPos);
  731. mat.mul(mObjToWorld, nodeMat);
  732. mat.affineInverse();
  733. }
  734. else
  735. {
  736. mat = mWorldToObj;
  737. }
  738. mat.mulP(targetPos, &toTarget);
  739. // lead the target
  740. F32 timeToTargetSquared = (mWeaponLeadVelocitySquared > 0) ? toTarget.lenSquared() / mWeaponLeadVelocitySquared : 0;
  741. if (timeToTargetSquared > 1.0)
  742. {
  743. targetPos = targetPos + (mTarget.lastVel * mSqrt(timeToTargetSquared));
  744. mat.mulP(targetPos, &toTarget);
  745. }
  746. F32 yaw, pitch;
  747. MathUtils::getAnglesFromVector(toTarget, yaw, pitch);
  748. if (yaw > M_PI_F)
  749. yaw = yaw - M_2PI_F;
  750. //if (pitch > M_PI_F)
  751. // pitch = -(pitch - M_2PI_F);
  752. Point3F rot(-pitch, 0.0f, yaw);
  753. // If we have a rotation rate make sure we follow it
  754. if (mHeadingRate > 0)
  755. {
  756. F32 rate = mHeadingRate * dt;
  757. F32 rateCheck = mFabs(rot.z - mRot.z);
  758. if (rateCheck > rate)
  759. {
  760. // This will clamp the new value to the rate regardless if it
  761. // is increasing or decreasing.
  762. rot.z = mClampF(rot.z, mRot.z-rate, mRot.z+rate);
  763. }
  764. }
  765. if (mPitchRate > 0)
  766. {
  767. F32 rate = mPitchRate * dt;
  768. F32 rateCheck = mFabs(rot.x - mRot.x);
  769. if (rateCheck > rate)
  770. {
  771. // This will clamp the new value to the rate regardless if it
  772. // is increasing or decreasing.
  773. rot.x = mClampF(rot.x, mRot.x-rate, mRot.x+rate);
  774. }
  775. }
  776. // Test if the rotation to the target is outside of our limits
  777. if (_outsideLimits(rot))
  778. {
  779. // We can't track any more
  780. _cleanupTargetAndTurret();
  781. return;
  782. }
  783. // Test if the target is out of weapons range
  784. if (toTarget.lenSquared() > mWeaponRangeSquared)
  785. {
  786. // We can't track any more
  787. _cleanupTargetAndTurret();
  788. return;
  789. }
  790. mRot = rot;
  791. _setRotation( mRot );
  792. setMaskBits(TurretUpdateMask);
  793. }
  794. void AITurretShape::_cleanupTargetAndTurret()
  795. {
  796. _lostTarget();
  797. resetTarget();
  798. }
  799. bool AITurretShape::_testTargetLineOfSight(Point3F& aimPoint, ShapeBase* target, Point3F& sightPoint)
  800. {
  801. Point3F targetCenter = target->getBoxCenter();
  802. RayInfo ri;
  803. bool hit = false;
  804. target->disableCollision();
  805. // First check for a clear line of sight to the target's center
  806. Point3F testPoint = targetCenter;
  807. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  808. if (hit)
  809. {
  810. // No clear line of sight to center, so try to the target's right. Players holding
  811. // a gun in their right hand will tend to stick their right shoulder out first if
  812. // they're peering around some cover to shoot, like a wall.
  813. Box3F targetBounds = target->getObjBox();
  814. F32 radius = targetBounds.len_x() > targetBounds.len_y() ? targetBounds.len_x() : targetBounds.len_y();
  815. radius *= 0.5;
  816. VectorF toTurret = aimPoint - targetCenter;
  817. toTurret.normalizeSafe();
  818. VectorF toTurretRight = mCross(toTurret, Point3F::UnitZ);
  819. testPoint = targetCenter + toTurretRight * radius;
  820. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  821. if (hit)
  822. {
  823. // No clear line of sight to right, so try the target's left
  824. VectorF toTurretLeft = toTurretRight * -1.0f;
  825. testPoint = targetCenter + toTurretLeft * radius;
  826. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  827. }
  828. if (hit)
  829. {
  830. // No clear line of sight to left, so try the target's top
  831. testPoint = targetCenter;
  832. testPoint.z += targetBounds.len_z() * 0.5f;
  833. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  834. }
  835. if (hit)
  836. {
  837. // No clear line of sight to top, so try the target's bottom
  838. testPoint = targetCenter;
  839. testPoint.z -= targetBounds.len_z() * 0.5f;
  840. hit = gServerContainer.castRay(aimPoint, testPoint, sAimTypeMask, &ri);
  841. }
  842. }
  843. target->enableCollision();
  844. if (!hit)
  845. {
  846. // Line of sight point is that last one we tested
  847. sightPoint = testPoint;
  848. }
  849. return !hit;
  850. }
  851. //----------------------------------------------------------------------------
  852. void AITurretShape::setAllGunsFiring(bool fire)
  853. {
  854. setImageTriggerState(0,fire);
  855. setImageTriggerState(1,fire);
  856. setImageTriggerState(2,fire);
  857. setImageTriggerState(3,fire);
  858. }
  859. void AITurretShape::setGunSlotFiring(S32 slot, bool fire)
  860. {
  861. if (slot < 0 || slot > 3)
  862. return;
  863. setImageTriggerState(slot, fire);
  864. }
  865. //----------------------------------------------------------------------------
  866. void AITurretShape::setTransform(const MatrixF& mat)
  867. {
  868. Parent::setTransform(mat);
  869. // Set the scanning box
  870. _setScanBox();
  871. }
  872. void AITurretShape::recenterTurret()
  873. {
  874. mRot.set(0,0,0);
  875. _setRotation( mRot );
  876. setMaskBits(TurretUpdateMask);
  877. }
  878. void AITurretShape::_setScanBox()
  879. {
  880. mTransformedScanBox = mScanBox;
  881. MatrixF mat;
  882. getScanTransform(mat);
  883. mat.mul(mTransformedScanBox);
  884. }
  885. void AITurretShape::getScanTransform(MatrixF& mat)
  886. {
  887. if (mDataBlock && mDataBlock->scanNode != -1)
  888. {
  889. if (getNodeTransform(mDataBlock->scanNode, mat))
  890. {
  891. return;
  892. }
  893. }
  894. mat = mObjToWorld;
  895. }
  896. void AITurretShape::getAimTransform(MatrixF& mat)
  897. {
  898. if (mDataBlock && mDataBlock->aimNode != -1)
  899. {
  900. if (getNodeTransform(mDataBlock->aimNode, mat))
  901. {
  902. return;
  903. }
  904. }
  905. mat = mObjToWorld;
  906. }
  907. //----------------------------------------------------------------------------
  908. void AITurretShape::processTick(const Move* move)
  909. {
  910. Parent::processTick(move);
  911. if (isServerObject() && mDamageState == Enabled)
  912. {
  913. _updateTurretState(TickSec);
  914. if (mScanForTargets)
  915. {
  916. // Perform a scan for targets
  917. _performScan();
  918. // If we found one, turn off the scan
  919. if (mTarget.isValid())
  920. {
  921. mScanForTargets = false;
  922. }
  923. }
  924. if (mTrackTarget)
  925. {
  926. _trackTarget(TickSec);
  927. // If the target is lost, no longer track it
  928. if (!mTarget.isValid())
  929. {
  930. mTrackTarget = false;
  931. }
  932. }
  933. }
  934. }
  935. void AITurretShape::advanceTime(F32 dt)
  936. {
  937. // If there were any ShapeBase script threads that
  938. // have played, then we need to update all code
  939. // controlled nodes. This is done before the Parent
  940. // call as script threads may play and be destroyed
  941. // before our code is called.
  942. bool updateNodes = false;
  943. for (U32 i = 0; i < MaxScriptThreads; i++)
  944. {
  945. Thread& st = mScriptThread[i];
  946. if (st.thread)
  947. {
  948. updateNodes = true;
  949. break;
  950. }
  951. }
  952. Parent::advanceTime(dt);
  953. // Update any state thread
  954. AITurretShapeData::StateData& stateData = *mState;
  955. if (mStateAnimThread && stateData.sequence != -1)
  956. {
  957. mShapeInstance->advanceTime(dt,mStateAnimThread);
  958. updateNodes = true;
  959. }
  960. if (updateNodes)
  961. {
  962. // Update all code controlled nodes
  963. _updateNodes(mRot);
  964. }
  965. }
  966. //----------------------------------------------------------------------------
  967. U32 AITurretShape::packUpdate(NetConnection *connection, U32 mask, BitStream *bstream)
  968. {
  969. U32 retMask = Parent::packUpdate(connection,mask,bstream);
  970. // Indicate that the transform has changed to update the scan box
  971. bstream->writeFlag(mask & (PositionMask | ExtendedInfoMask));
  972. // Handle any state changes that need to be passed along
  973. if (bstream->writeFlag(mask & TurretStateMask))
  974. {
  975. bstream->write(mDataBlock->lookupState(mState->name));
  976. }
  977. return retMask;
  978. }
  979. void AITurretShape::unpackUpdate(NetConnection *connection, BitStream *bstream)
  980. {
  981. Parent::unpackUpdate(connection,bstream);
  982. // Transform has changed
  983. if (bstream->readFlag())
  984. {
  985. _setScanBox();
  986. }
  987. //TurretStateMask
  988. if (bstream->readFlag())
  989. {
  990. S32 newstate;
  991. bstream->read( &newstate );
  992. setTurretState(newstate);
  993. }
  994. }
  995. //----------------------------------------------------------------------------
  996. void AITurretShape::prepBatchRender( SceneRenderState *state, S32 mountedImageIndex )
  997. {
  998. Parent::prepBatchRender( state, mountedImageIndex );
  999. if ( !gShowBoundingBox )
  1000. return;
  1001. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1002. ri->renderDelegate.bind( this, &AITurretShape::_renderScanner );
  1003. ri->type = RenderPassManager::RIT_Editor;
  1004. state->getRenderPass()->addInst( ri );
  1005. }
  1006. void AITurretShape::_renderScanner( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  1007. {
  1008. GFXStateBlockDesc desc;
  1009. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1010. desc.setZReadWrite(false,true);
  1011. desc.fillMode = GFXFillWireframe;
  1012. // Render the scan box
  1013. GFX->getDrawUtil()->drawCube(desc, mTransformedScanBox.getExtents(), mTransformedScanBox.getCenter(), ColorI(255, 0, 0));
  1014. // Render a line from the scan node to the max scan distance
  1015. MatrixF nodeMat;
  1016. if (getNodeTransform(mDataBlock->scanNode, nodeMat))
  1017. {
  1018. Point3F start;
  1019. nodeMat.getColumn(3, &start);
  1020. Point3F end(0.0f, mScanDistance, 0.0f);
  1021. nodeMat.mulP(end);
  1022. GFX->getDrawUtil()->drawLine(start, end, ColorI(255, 255, 0));
  1023. }
  1024. }
  1025. //----------------------------------------------------------------------------
  1026. DefineEngineMethod( AITurretShape, addToIgnoreList, void, (ShapeBase* obj),,
  1027. "@brief Adds object to the turret's ignore list.\n\n"
  1028. "All objects in this list will be ignored by the turret's targeting.\n"
  1029. "@param obj The ShapeBase object to ignore.\n")
  1030. {
  1031. object->addToIgnoreList(obj);
  1032. }
  1033. DefineEngineMethod( AITurretShape, removeFromIgnoreList, void, (ShapeBase* obj),,
  1034. "@brief Removes object from the turret's ignore list.\n\n"
  1035. "All objects in this list will be ignored by the turret's targeting.\n"
  1036. "@param obj The ShapeBase object to once again allow for targeting.\n")
  1037. {
  1038. object->removeFromIgnoreList(obj);
  1039. }
  1040. DefineEngineMethod( AITurretShape, clearIgnoreList, void, (),,
  1041. "@brief Removes all objects from the turret's ignore list.\n\n"
  1042. "All objects in this list will be ignored by the turret's targeting.\n")
  1043. {
  1044. object->clearIgnoreList();
  1045. }
  1046. DefineEngineMethod( AITurretShape, ignoreListCount, S32, (),,
  1047. "@brief Returns the number of objects in the turrets ignore list.\n\n"
  1048. "All objects in this list will be ignored by the turret's targeting.\n")
  1049. {
  1050. return object->ignoreListCount();
  1051. }
  1052. DefineEngineMethod( AITurretShape, getIgnoreListObject, SimObject*, (S32 index),,
  1053. "@brief Returns the object in the ignore list at index.\n\n"
  1054. "All objects in this list will be ignored by the turret's targeting.\n"
  1055. "@param index The index of the object in the ignore list being retrieved.\n")
  1056. {
  1057. return object->getIgnoreListObject(index);
  1058. }
  1059. DefineEngineMethod( AITurretShape, setTurretState, void, (const char* newState, bool force), (false),
  1060. "@brief Set the turret's current state.\n\n"
  1061. "Normally the turret's state comes from updating the state machine but this method "
  1062. "allows you to override this and jump to the requested state immediately.\n"
  1063. "@param newState The name of the new state.\n"
  1064. "@param force Is true then force the full processing of the new state even if it is the "
  1065. "same as the current state. If false then only the time out value is reset and the state's "
  1066. "script method is called, if any.\n")
  1067. {
  1068. object->setTurretStateName(newState, force);
  1069. }
  1070. DefineEngineMethod( AITurretShape, activateTurret, void, ( ),,
  1071. "@brief Activate a turret from a deactive state.\n\n")
  1072. {
  1073. object->activateTurret();
  1074. }
  1075. DefineEngineMethod( AITurretShape, deactivateTurret, void, ( ),,
  1076. "@brief Deactivate a turret from an active state.\n\n")
  1077. {
  1078. object->deactivateTurret();
  1079. }
  1080. DefineEngineMethod( AITurretShape, startScanForTargets, void, ( ),,
  1081. "@brief Begin scanning for a target.\n\n")
  1082. {
  1083. object->startScanForTargets();
  1084. }
  1085. DefineEngineMethod( AITurretShape, stopScanForTargets, void, ( ),,
  1086. "@brief Stop scanning for targets.\n\n"
  1087. "@note Only impacts the scanning for new targets. Does not effect a turret's current "
  1088. "target lock.\n")
  1089. {
  1090. object->stopScanForTargets();
  1091. }
  1092. DefineEngineMethod( AITurretShape, startTrackingTarget, void, ( ),,
  1093. "@brief Have the turret track the current target.\n\n")
  1094. {
  1095. object->startTrackingTarget();
  1096. }
  1097. DefineEngineMethod( AITurretShape, stopTrackingTarget, void, ( ),,
  1098. "@brief Stop the turret from tracking the current target.\n\n")
  1099. {
  1100. object->stopTrackingTarget();
  1101. }
  1102. DefineEngineMethod( AITurretShape, hasTarget, bool, (),,
  1103. "@brief Indicates if the turret has a target.\n\n"
  1104. "@returns True if the turret has a target.\n")
  1105. {
  1106. return object->hasTarget();
  1107. }
  1108. DefineEngineMethod( AITurretShape, getTarget, SimObject*, (),,
  1109. "@brief Get the turret's current target.\n\n"
  1110. "@returns The object that is the target's current target, or 0 if no target.\n")
  1111. {
  1112. return object->getTarget();
  1113. }
  1114. DefineEngineMethod( AITurretShape, resetTarget, void, ( ),,
  1115. "@brief Resets the turret's target tracking.\n\n"
  1116. "Only resets the internal target tracking. Does not modify the turret's facing.\n")
  1117. {
  1118. object->resetTarget();
  1119. }
  1120. DefineEngineMethod( AITurretShape, setWeaponLeadVelocity, void, (F32 velocity),,
  1121. "@brief Set the turret's projectile velocity to help lead the target.\n\n"
  1122. "This value normally comes from AITurretShapeData::weaponLeadVelocity but this method "
  1123. "allows you to override the datablock value. This can be useful if the turret changes "
  1124. "ammunition, uses a different weapon than the default, is damaged, etc.\n"
  1125. "@note Setting this to 0 will disable target leading.\n")
  1126. {
  1127. object->setWeaponLeadVelocity(velocity);
  1128. }
  1129. DefineEngineMethod( AITurretShape, getWeaponLeadVelocity, F32, (),,
  1130. "@brief Get the turret's defined projectile velocity that helps with target leading.\n\n"
  1131. "@returns The defined weapon projectile speed, or 0 if leading is disabled.\n")
  1132. {
  1133. return object->getWeaponLeadVelocity();
  1134. }
  1135. DefineEngineMethod( AITurretShape, setAllGunsFiring, void, (bool fire),,
  1136. "@brief Set the firing state of the turret's guns.\n\n"
  1137. "@param fire Set to true to activate all guns. False to deactivate them.\n")
  1138. {
  1139. object->setAllGunsFiring(fire);
  1140. }
  1141. DefineEngineMethod( AITurretShape, setGunSlotFiring, void, (S32 slot, bool fire),,
  1142. "@brief Set the firing state of the given gun slot.\n\n"
  1143. "@param slot The gun to modify. Valid range is 0-3 that corresponds to the weapon mount point.\n"
  1144. "@param fire Set to true to activate the gun. False to deactivate it.\n")
  1145. {
  1146. object->setGunSlotFiring(slot, fire);
  1147. }
  1148. DefineEngineMethod( AITurretShape, recenterTurret, void, ( ),,
  1149. "@brief Recenter the turret's weapon.\n\n")
  1150. {
  1151. object->recenterTurret();
  1152. }